Swift Xcode 6.1.1 POST request is not published
I just want to POST some data from Swift to a PHP script. I've been Googled for two days now and everyone seems to be doing the same thing, but it doesn't work for me. I have this Swift code running on viewDidLoad ()
override func viewDidLoad() {
super.viewDidLoad()
let request = NSMutableURLRequest(URL: NSURL(string: "http://mywebsite.com/scriptToHandlePOST.php")!) // it forces me to add the !
request.HTTPMethod = "POST"
var err: NSError?
let postString = "var1=value1&var2=value2".dataUsingEncoding(NSUTF8StringEncoding)
var postLength:NSString = String( postString!.length )
request.HTTPBody = postString
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println(response) // this returns a 200
println(strData!) // this returns an empty array of the $_POST variable
}
task.resume() // this is needed to start the task
}
My PHP script is just trying to get the $ _POST data:
<?php
print_r($_POST);
?>
Since $ _POST returns an empty array, I suspect that the POST request never gets to my site. Do you see something wrong in the code?
+3
source to share
No one has answered this question yet
Check out similar questions: