我正在运行一个简短的 Swift 脚本来将一些变量发布到一个 PHP 脚本中,然后读取返回值:
let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/createCommunity.php");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = "communityname=\(communityName!)&code=\(communityCode)&email=\(myEmail!)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
print (json["code"]);
print (json["email"]);
print (json["communityname"]);
}
task.resume()
}
在我下面的 PHP 代码中,我只想接收值,然后将它们返回到一个数组中:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require("Conn.php");
require("MySQLDao.php");
$email = htmlentities($_POST["email"]);
$code = htmlentities($_POST["code"]);
$communityname = htmlentities($_POST["communityname"]);
$returnValue = array();
$returnValue["code"] = $code;
$returnValue["email"] = $email;
$returnValue["communityname"] = $communityname;
echo json_encode($returnValue);
?>
我知道我在 Swift 代码的末尾做错了什么,但我不知道是什么。
我在 let task
行收到此错误:
从类型“(Data?, URLResponse?, Error?) throws -> ()”到非抛出函数类型“(Data?, URLResponse?, Error?) -> Void 的无效转换'
最佳答案
也许您没有包含所有代码,但是...您是在调用 task.resume()
吗?
试试这个:
let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/createCommunity.php");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = "communityname=\(communityName!)&code=\(communityCode)&email=\(myEmail!)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let json = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject] {
print (json["code"]);
print (json["email"]);
print (json["communityname"]);
}
}
task.resume()
关于ios - 如何获取这段 Swift 代码以接收 PHP 脚本的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40086089/