【问题标题】:Can't urlencode deviceToken (Swift)无法对 deviceToken 进行 urlencode (Swift)
【发布时间】:2015-03-09 00:57:34
【问题描述】:

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

错误:“致命错误:在展开可选值时意外发现 nil”

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

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

【问题讨论】:

  • "[http://example.com]&deviceToken=\(deviceToken)" 应该是 "http://example.com&deviceToken=\(deviceToken)",不带方括号。你从哪里得到的?
  • 其实应该是"http://example.com?deviceToken=\(deviceToken)"

标签: swift ios8 nsdata nsurl


【解决方案1】:

你能确定什么变量被解包并返回 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() 

}

【讨论】:

  • 非常感谢。我试图解开 deviceToken,所以你的解决方案工作正常。
  • @Matt 很高兴我能帮上忙 :)
  • 非常小的评论 - format: "%02hhx" 就足够了。不需要精度,因为device token 的每个字节都是整数。见pubs.opengroup.org/onlinepubs/009695399/functions/printf.html
  • 这在 Xcode 7.3 中已弃用,请更新您的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-03
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2010-09-22
  • 1970-01-01
相关资源
最近更新 更多