Scar
Scar

Reputation: 385

Swift 2.0 - Store JSON value from swift to a php variable and display using php echo

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

Upvotes: 1

Views: 183

Answers (2)

Ankit vadariya
Ankit vadariya

Reputation: 1263

Please check mod_rewrite PHP / Apache Module.

You need to enable that module.

Upvotes: 0

Ammo
Ammo

Reputation: 580

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.

Upvotes: 1

Related Questions