我要做什么来使用swift从DB(MySQL)获取,发布和检查数据? 我可以只创建php页面并联系他们,还是有办法管理它们?如果有,怎么样?
答案 0 :(得分:7)
(对不起我的英文)
是的,你需要一个PHP脚本
在你的swift文件中:
var bodyData = "name=value" //To get them in php: $_POST['name']
let URL: NSURL = NSURL(string: "URL TO YOUR PHP FILE")
let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
var output = NSString(data: data, encoding: NSUTF8StringEncoding) // new output variable
var array = self.JSONParseArray(output)
}
在php中:
function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
$status_header = 'HTTP/1.1 ' . $status;
header($status_header);
header('Content-type: ' . $content_type);
echo $body;
}
$name = $_POST['name']; // Like in the bodyData var
//Doing sql things
$result = array(
"result" => "VARIABLE TO SEND BACK"
);
sendResponse(200, json_encode($result));
如果您不想在数组中得到结果,请使用此函数:
func JSONParseArray(jsonString: String) -> Array<String> {
var e: NSError?
var data: NSData!=jsonString.dataUsingEncoding(NSUTF8StringEncoding)
var jsonObj = NSJSONSerialization.JSONObjectWithData(
data,
options: NSJSONReadingOptions(0),
error: &e) as Array<String>
if e == 0 {
return Array<String>()
} else {
return jsonObj
}
}