I want to save my users tokens id into my database using POST request in Swift (here PHP code here). I am a bit confused about synchronous and asynchronous request.
- Is this code the right way to do it?
- would the app crash if there is a connection problem while it is sending the synchronous request
- shall I use an api key (not sure is the correct word) to "identify" the user
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
var userId = "001" //I just use it as USER number 1
// prepare the tolen to be saved from <xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx> to xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
var token = NSString(format: "%@", deviceToken)
token = token.stringByReplacingOccurrencesOfString(
"<",
withString: "")
token = token.stringByReplacingOccurrencesOfString(
">",
withString: "")
token = token.stringByReplacingOccurrencesOfString(" ", withString: "")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
var postBody = NSString(format: "user=%@&token=%@", userId, token)
var endBody = NSURL(string: "http://www.myServer.com/api/v1.0/saveToken.php")
var request = NSMutableURLRequest(URL: endBody!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 30.0)
request.HTTPMethod = "POST";
request.HTTPBody = postBody.dataUsingEncoding(NSUTF8StringEncoding)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
var response: NSURLResponse?
var error: NSError?
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
println(response)
println(error)
})
}