Revision 2bf6abdb-1bba-4668-a470-55e9daafb47b - Code Review Stack Exchange
This:
var token = NSString(format: "%@", deviceToken)
token = token.stringByReplacingOccurrencesOfString("<", withString: "")
token = token.stringByReplacingOccurrencesOfString(">", withString: "")
token = token.stringByReplacingOccurrencesOfString(" ", withString: "")
is actually a bad method to convert an `NSData` object to an `NSString`
(containing the bytes in hexadecimal). It relies on `description`
having the format
<01020304 05060708 090a0b0c 0d0e0f10>
which is not officially documented. In most cases, the `description` of
an object is only suitable for debugging purposes, but not for further
processing.
I would convert all data bytes explicitly to create the string. Here is a possible implementation as an `NSData` extension method:
extension NSData {
func hexString() -> String {
// "Array" of all bytes:
let bytes = UnsafeBufferPointer<UInt8>(start: UnsafePointer(self.bytes), count:self.length)
// Array of hex strings, one for each byte:
let hexBytes = map(bytes) { String(format: "%02hhx", 0ドル) }
// Concatenate all hex strings:
return "".join(hexBytes)
}
}
which can be used as
let token = deviceToken.hexString()
----------
With
dispatch_async(dispatch_get_main_queue(), { ... }
you dispatch the URL request to the *main queue* where it blocks the
UI. You can use `dispatch_get_global_queue()` instead to dispatch
it to a background thread, or simply use `sendAsynchronousRequest()`:
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response, data, error) -> Void in
if data != nil {
println("data: \(data)")
} else {
println("failed: \(error.localizedDescription)")
}
}
Now the request is done in the background and then the completion
handler called on the main thread.
In the case of an connection problem, the completion handler is called
with `data == nil` and `error != nil` containing information about the
problem.