EDIT: I'm developing an iOS application, which uses a webview, that has push notification and I'm trying to pass the device token to a php file (sampleIndex.php) for database registration.
My attempt on posting the device token isn't working. Here's the code:
EDIT (2): My current code is based from @mat 's answer (same concept, but cleaner)
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 = bytes.map { String(format: "%02hhx", $0) }
// Concatenate all hex strings:
return (hexBytes).joinWithSeparator("")
}
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let session = NSURLSession.sharedSession()
let tk = deviceToken.hexString()
let postBody = NSString(format: "token=%@", tk)
let endBody = NSURL(string: "http://samplesite.com/subfolder/subfolder2/sampleIndex.php")
let 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")
let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if data != nil {
print("data: \(response)")
} else {
print("failed: \(error!.localizedDescription)")
}
}//closure
dataTask.resume()
}
Why can't I get the value of tk? (token device). Am I missing something? Sorry, I'm just new to this.
EDIT (3) Here's the php code (sampleIndex.php) where the token is being requested:
<?php
include_once("includes/myConnect.php");
$token = $_REQUEST['token'];
if (empty($token)) {
$sql = "UPDATE sampleDB . sampleTB SET token= '0' WHERE id='8982'";
$result = mysqli_query($conn, $sql);
}else{
$sql = "UPDATE sampleDB . sampleTB SET token= '1' WHERE id='8982'";
$result = mysqli_query($conn, $sql);
}
?>
(token sets to value " 0 " which proves that the device token fails to be passed on sampleIndex.php)