swift 3.0 Data to String?
I came looking for the answer to the Swift 3 Data to String question and never got a good answer. After some fooling around I came up with this:
var testString = "This is a test string"
var somedata = testString.data(using: String.Encoding.utf8)
var backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String!
let str = deviceToken.map { String(format: "%02hhx", $0) }.joined()
I found the way to do it. You need to convert Data
to NSData
:
let characterSet = CharacterSet(charactersIn: "<>")
let nsdataStr = NSData.init(data: deviceToken)
let deviceStr = nsdataStr.description.trimmingCharacters(in: characterSet).replacingOccurrences(of: " ", with: "")
print(deviceStr)
here is my data extension. add this and you can call data.ToString()
import Foundation
extension Data
{
func toString() -> String?
{
return String(data: self, encoding: .utf8)
}
}