swift 3.0 Data to String?
SwiftStringSwift Problem Overview
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {}
I want deviceToken
to string
but:
let str = String.init(data: deviceToken, encoding: .utf8)
str
is nil
swift 3.0
how can I let data
to string
?
https://stackoverflow.com/questions/37956482/registering-for-push-notifications-in-xcode-8-swift-3-0 not working and the answer is a few months ago, I had tried it:
and print:
Swift Solutions
Solution 1 - Swift
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!
Solution 2 - Swift
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)
}
}
Solution 3 - Swift
let str = deviceToken.map { String(format: "%02hhx", $0) }.joined()
Solution 4 - Swift
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)
Solution 5 - Swift
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()
}
}
Solution 6 - Swift
Swift 4 version of 4redwings's answer:
let testString = "This is a test string"
let somedata = testString.data(using: String.Encoding.utf8)
let backToString = String(data: somedata!, encoding: String.Encoding.utf8)
Solution 7 - Swift
You can also use let data = String(decoding: myStr, as: UTF8.self)
here is a resource about converting data to string
Solution 8 - Swift
for swift 5
let testString = "This is a test string"
let somedata = testString.data(using: String.Encoding.utf8)
let backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String?
print("testString > \(testString)")
//testString > This is a test string
print("somedata > \(String(describing: somedata))")
//somedata > Optional(21 bytes)
print("backToString > \(String(describing: backToString))")
//backToString > Optional("This is a test string")
Solution 9 - Swift
To extend on the answer of weijia.wang:
extension Data {
func hexString() -> String {
let nsdataStr = NSData.init(data: self)
return nsdataStr.description.trimmingCharacters(in: CharacterSet(charactersIn: "<>")).replacingOccurrences(of: " ", with: "")
}
}
use it with deviceToken.hexString()
Solution 10 - Swift
According to the Apple doc below, device token can not be decoded. So, I think the best thing to do is just leave it be.
> https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html > > Security Architecture > > A device token is an opaque NSData instance that contains a unique identifier assigned by Apple to a specific app on a specific device. Only APNs can decode and read the contents of a device token. Each app instance receives its unique device token when it registers with APNs, and must then forward the token to its provider, as described in Configuring Remote Notification Support. The provider must include the device token in each push notification request that targets the associated device; APNs uses the device token to ensure the notification is delivered only to the unique app-device combination for which it is intended.
Solution 11 - Swift
If your data is base64 encoded.
if ( dataObj != nil ) {
let encryptedDataText = dataObj!.base64EncodedString(options: NSData.Base64EncodingOptions())
NSLog("Encrypted with pubkey: %@", encryptedDataText)
}
Solution 12 - Swift
let urlString = baseURL + currency
if let url = URL(string: urlString){
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url){ (data, reponse, error) in
if error != nil{
print(error)
return
}
let dataString = String(data: data!, encoding: .utf8)
print(dataString)
}
task.resume()
}