我遇到以下代码的问题,它适用于iphone 5s模拟器。但是当我连接我的iphone5s设备时,它不起作用。通过模拟器,我从swiftupload.php获得了这个(如预期的那样)
Button pressed <- swift
responseString = Optional({"message":"some variable"}Success) <- from php
Email has ben sent <- swift
随着我的设备连接,我得到了
Button pressed
responseString = Optional()
php文件看起来像:
$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);
这是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")
}
答案 0 :(得分:1)
在iPhone上, localhost 是iPhone的IP。 将“ localhost ”替换为MAC / PC的IP并检查应用传输安全性异常https://stackoverflow.com/a/30732693/4755417