0

I'm trying to post from swift to php and then return json encoded data back to swift.

However, print(task.response) is nil. My link does what it is supposed to but my app still responds with nil. Any idea why?

let request = NSMutableURLRequest(URL: NSURL(string: "https://www.flashkase.com/API/createAccount.php")!)
request.HTTPMethod = "POST"
let postString = "username=frogg222"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
    guard error == nil && data != nil else { // check for fundamental networking error
        print("error=\(error)")
        return
    }

    if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
        print("statusCode should be 200, but is \(httpStatus.statusCode)")
        print("response = \(response)")
    }

    let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
    print("responseString = \(responseString)")
}
task.resume()
print(task.response)

And my PHP file

<?php 
include($_SERVER["DOCUMENT_ROOT"] . "/inc/database.php");
$arr = [];

$arr[] = 'Reporting for duty';

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $arr[] = 'Post received';
    $arr[] = $_POST['username'];
}

echo json_encode($arr);
?>

Update: How can I check for data after completion? If I uncomment sleep(3) it will display results...but that's obviously not ideal.

func postToServer(postURL: String, postString: String) {

    let request = NSMutableURLRequest(URL: NSURL(string: postURL)!)
    request.HTTPMethod = "POST"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
        data, response, error in 

        print("\(data), \(response), \(error)")

    }
    task.resume()
    //sleep(3)
}


let sendURL: String = "https://www.flashkase.com/API/createAccount.php"
let sendData: String = "username=frogg222&[email protected]&password=fake1234"

postToServer(sendURL,postString: sendData)
0

1 Answer 1

1

dataTaskWithRequest is an asynchronous operation. Printing the response code immediately after the task starts will obviously print nil, as it hasn't had time to get a value. The completion handler already has a response object you can use, so inside your completion handler, call print(response) to see the properties and try to get a response code.

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

15 Comments

I'm kind of new to swift, which is the completion handler? and/or how can I make one?
Your completion handler is everything the dataTaskWithRequest(request) {...} (where ... is your code).
I'm sorry man, it's still not working. Any chance you can provide an example? I placed sleep(3) before print(task.response) and it finally gave me the response but no data.
sleep(3) worked because you gave the network operation enough time to complete and to have a response code before calling print. That is not an ideal solution. You could just put it above guard error == nil && data != nil else {.
I've updated my post, I still can't figure out how to check after completion, can you provide an example please?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.