2015-01-10 4 views
0

내 서버에 NSURL 세션을 사용하여 deviceToken을 보내려고하지만 매번 충돌합니다. DataObject (deviceToken)를 NSString으로 변환하는 방법을 찾으려고했지만 지금까지 성공하지 못했습니다.deviceToken (스위프트)을 urlencode 할 수 없습니다.

오류 : "치명적인 오류 : 예기치 않게하는 옵션 값 풀기 동안 전무 발견"

어떤 도움의이 크게 감사합니다. 내 코드는 다음과 같습니다

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

' "[http://example.com] deviceToken = \ (deviceToken)는"' "'해야 HTTP : //example.com&deviceToken= \ (deviceToken) ", 대괄호없이. 어디서 났어? –

+1

실제로는 "http://example.com?deviceToken=\(deviceToken)"'이어야합니다. –

답변

4

언 래핑 된 변수를 찾아 내고 nil을 반환 할 수 있습니까? URL을 제외하고는 아무 것도 볼 수 없으므로 오류가 잘못된 URL 일 수 있습니다. NSURL은 엄격한 구문 (RFC 2396)에 따라 주어진 문자열의 유효성을 확인합니다. 합니다 (deviceToken없이)이 URL을 시도하고 그 어떤 차이가 있는지 :

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

} 
+0

고마워요. deviceToken을 unwrap하려고 했으므로 솔루션이 잘 작동합니다. – Matt

+0

@Matt Glad 나는 도울 수 있었다 : – Emil

+1

아주 사소한 의견 -'''format : "% 02hhx"'''충분하다. '''device token''의 모든 바이트가 정수이므로 정밀도가 필요 없습니다. http://pubs.opengroup.org/onlinepubs/009695399/functions/printf.html –