weijia.wang
weijia.wang

Reputation: 2168

swift 3.0 Data to String?

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 ?

Registering for Push Notifications in Xcode 8/Swift 3.0? not working and the answer is a few months ago, I had tried it:

enter image description here

and print:

enter image description here

Upvotes: 98

Views: 139764

Answers (12)

Zgpeace
Zgpeace

Reputation: 4467

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")

Upvotes: 1

user12739102
user12739102

Reputation: 1

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()

    }

Upvotes: 0

atalayasa
atalayasa

Reputation: 3490

You can also use let data = String(decoding: myStr, as: UTF8.self) here is a resource about converting data to string

Upvotes: 1

Kyle Bing
Kyle Bing

Reputation: 179

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.

Upvotes: 0

luhuiya
luhuiya

Reputation: 2211

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)
    }
}

Upvotes: 39

jeet.chanchawat
jeet.chanchawat

Reputation: 2575

If your data is base64 encoded.

if ( dataObj != nil ) {
    let encryptedDataText = dataObj!.base64EncodedString(options: NSData.Base64EncodingOptions())
    NSLog("Encrypted with pubkey: %@", encryptedDataText)
}

Upvotes: 0

Abhishek Jain
Abhishek Jain

Reputation: 4739

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)

Upvotes: 2

weijia.wang
weijia.wang

Reputation: 2168

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)

Upvotes: 7

Gargoyle
Gargoyle

Reputation: 10336

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()
    }
}

Upvotes: 2

Markus
Markus

Reputation: 598

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()

Upvotes: 0

Hogdotmac
Hogdotmac

Reputation: 347

let str = deviceToken.map { String(format: "%02hhx", $0) }.joined()

Upvotes: 19

4redwings
4redwings

Reputation: 1826

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!

Upvotes: 171

Related Questions