无法对 deviceToken 进行 urlencode (Swift)

Can't urlencode deviceToken (Swift)

我想使用 NSURL 会话将 deviceToken 发送到我的服务器,但它每次都会崩溃。我试图找到一种将 DataObject(deviceToken)转换为 NSString 的方法,但到目前为止没有成功。

错误:"fatal error: unexpectedly found nil while unwrapping an Optional value"

非常感谢任何帮助。这是我的代码

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken   deviceToken: NSData!) {
    let urlPath = "http://example.com/deviceToken=\(deviceToken)"
    let url = NSURL(string: urlPath)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
        if(error != nil) {
            // If there is an error in the web request, print it to the console
            println(error.localizedDescription)
        }
        var err: NSError?

    })

    task.resume()  
}

你能指出哪个变量被解包并返回 nil 吗?除了 URL,我看不到任何会导致这种情况的原因,因此您的错误可能是无效的 URL。请记住 NSURL 根据严格的语法 (RFC 2396) 验证给定的字符串。试试这个 URL(没有 deviceToken),看看是否有什么不同:

let urlPath = "http://example.com/?deviceToken"

旁注,设备令牌需要 URL 编码,请参阅 this answer。您的整个方法将如下所示:

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

    for var i = 0; i < deviceToken.length; i++ {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }
    let urlPath = "http://example.com/?deviceToken=\(tokenString)"
    let url = NSURL(string: urlPath)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
        if(error != nil) {
            // If there is an error in the web request, print it to the console
            println(error.localizedDescription)
        }
        var err: NSError?

    })

    task.resume() 

}