I have configured the notifications using GCM and to send them later, I need to register the tokens in my database. First of all in my AppDelegate, I store the token in the following way:
let deviceTokenString = NSString(format: "%@", deviceToken) as String
NSUserDefaults.standardUserDefaults().setObject(deviceTokenString, forKey: "deviceToken")
NSUserDefaults.standardUserDefaults().synchronize()
After this, in another screen I make a Post that I have verified that it works since a certain value or even another variable is published without any problem, but the token does not do it. For example, in this code, the variable otra
would be published but tokenstring
does not.
var tokenstring = NSUserDefaults.standardUserDefaults().objectForKey("deviceToken")
var otra = "prueba"
...
let request = NSMutableURLRequest(URL: NSURL(string: "http://elpenitente.playcofrade.com/post/registrar-ios.php")!)
request.HTTPMethod = "POST"
let token = "token=\(self.tokenstring)&so=ios"
request.HTTPBody = token.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else {
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
On the other hand, I created a function to be able to see the value stored in that value of NSUserDefaults
and the token is shown so the failure should not be there either. What can be happening?