Reputation: 4914
I am having an issue with the following code, it works on the iphone 5s simulator. But when i attach my iphone5s device it doesn't work. With the simulator i get this (as expected) back from swiftupload.php
Button pressed <- swift
responseString = Optional({"message":"some variable"}Success) <- from php
Email has ben sent <- swift
And with my device attached i get
Button pressed
responseString = Optional()
The php file looks like:
$postdata = json_decode(file_get_contents("php://input"), TRUE);
$message = $postdata["data"];
// Store values in an array
$returnValue = array("message" => $message);
// Send back request in JSON format
echo json_encode($returnValue);
And this is the function in swift
func postToServerFunction(){
// json php
let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost/mydomain.com/swiftupload.php")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let params = ["data":"some variable"] as Dictionary<String, String>
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
//Response print
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
if let HTTPResponse = response as? NSHTTPURLResponse {
let statusCode = HTTPResponse.statusCode
if statusCode == 200{
print("Email has ben sent")
}
}
})
task.resume()
print("Button pressed")
}
Upvotes: 0
Views: 513
Reputation: 1236
On the iPhone the localhost is IP of the iPhone. Replace "localhost" with IP of your MAC/PC and check App Transport Security exceptions https://stackoverflow.com/a/30732693/4755417
Upvotes: 1