swift 3.0數據到字符串?



string (6)

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {}

我希望 deviceToken 成為字符串

但:

let str = String.init(data: deviceToken, encoding: .utf8)

strnil

swift 3.0

我怎樣才能讓 data string

在Xcode 8 / Swift 3.0中註冊推送通知? 沒有工作,答案是幾個月前,我曾嘗試過:

並打印:

https://ffff65535.com


Swift 4版4redwings的答案:

let testString = "This is a test string"
let somedata = testString.data(using: String.Encoding.utf8)
let backToString = String(data: somedata!, encoding: String.Encoding.utf8)

在Swift 3和更高版本中使用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()
    }
}

延伸到weijia.wang的答案:

extension Data {
    func hexString() -> String {
        let nsdataStr = NSData.init(data: self)
        return nsdataStr.description.trimmingCharacters(in: CharacterSet(charactersIn: "<>")).replacingOccurrences(of: " ", with: "")
    }
}

deviceToken.hexString()


我來尋找Swift 3 Data to String問題的答案,從來沒有得到一個好的答案。 經過一番愚弄,我想到了這個:

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!


這是我的數據擴展。 添加這個,你可以調用data.ToString()

import Foundation

extension Data
{
    func toString() -> String?
    {
        return String(data: self, encoding: .utf8)
    }
}




string