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!
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)
}
}
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)
This is much easier in Swift 3 and later using reduce:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.reduce("") { $0 + String(format: "%02x", $1) }
DispatchQueue.global(qos: .background).async {
let url = URL(string: "https://example.com/myApp/apns.php")!
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = try! JSONSerialization.data(withJSONObject: [
"token" : token,
"ios" : UIDevice.current.systemVersion,
"languages" : Locale.preferredLanguages.joined(separator: ", ")
])
URLSession.shared.dataTask(with: request).resume()
}
}