首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法使用deviceToken (Swift)

无法使用deviceToken (Swift)
EN

Stack Overflow用户
提问于 2015-01-10 22:49:15
回答 1查看 1.3K关注 0票数 0

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

错误:“致命错误:在展开可选值时意外找到零”

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

代码语言:javascript
复制
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()  
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-10 23:28:04

你能准确地指出哪些变量正在被打开并返回零吗?除了URL之外,我看不到任何会导致这种情况的东西,所以您的错误可能是一个无效的URL。记住,NSURL根据严格的语法(RFC 2396)验证给定的字符串。试试这个URL (没有deviceToken),看看这是否有什么区别:

代码语言:javascript
复制
let urlPath = "http://example.com/?deviceToken"

在侧节点上,设备令牌需要进行URL编码,请参见这个答案。然后,您的整个方法如下:

代码语言:javascript
复制
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() 

}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27882009

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档