1

I'm trying to store the device token posted by swift, to a php variable for future references (like checking if the token already exists in the database).

This is my Swift code:

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

    let sampleToken = deviceToken.hexString()
    let session = NSURLSession.sharedSession()
    let postBody = NSString(format: "token=\(sampleToken)")
    let endBody = NSURL(string: "http://www.samplesite.com/sub1/sub2/testing.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)")
        }
    }
    dataTask.resume()    
}

This is my php file for token storage:

<?php

$token = $_REQUEST['token'];

var_dump(json_decode($token)); //returns null
var_dump(json_decode($token, true)); //returns null

include_once("includes/dbi_connect.php");

        $sql1 = "INSERT INTO tbs_main . userTokenInfo (token) VALUES ('".$token."')";
        $result = mysqli_query($conn, $sql1);
?>

What confuses me is that, the token is still recorded in the database but can't be displayed. I'm missing something here, and I really don't know where and what. Is there something wrong on the passing and converting of the device token? or it's in the php side?

UPDATE

I tried using var_dump('$token'); just as Ammo suggested, but it only returned a null value

2 Answers 2

1

You simply aren't sending a JSON from swift, its a pure HTTP request.

Try var_dump($token); in php instead of json_decode($token).

That's why you can see the token in db, but you are just trying to display it wrongly.

If you want you can use some library like Alamofire to send a json from swift.

Sign up to request clarification or add additional context in comments.

2 Comments

I've tried using var_dump and it still displays / returns a null value. Is there a problem in the swift part?
I also tried var_dump('$_POST'); and it returned array(0){}. So it seems php can't read the post request from swift
0

Please check mod_rewrite PHP / Apache Module.

You need to enable that module.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.