gpt4 book ai didi

php - swift php数组到swift json

转载 作者:行者123 更新时间:2023-11-28 07:00:52 25 4
gpt4 key购买 nike

我正在尝试使用 swift 代码将 vars 传递给 php,并将响应返回给 swift。使用以下代码一切顺利。这只是一段简单的代码,可以让事情顺利进行。它给了我正确的连接和结果,我必须如何传递我猜应该在数组中的数据负载。但是当我尝试通过数组发送更多数据时,我什么也看不到。在 php 中,我会分解结果以一个一个地获取它们,但是我如何为变量获取大量值以便我可以再次使用它们?

下面是我的代码

<?php
require('conn.php');
header('Content-type: application/json');
if($_POST) {
$database =trim ($_POST['database']);
$engine = trim($_POST['engine']);


$name = "William";


$results = Array("name" => $name
);



echo json_encode($results);
}/*end if POST*/

?>

这是swift代码

let data:NSString = ("bfdprofile" as NSString)
let engine:NSString = "account" as NSString

self.usernameLabel.text = prefs.valueForKey("USERNAME") as? String




let url = NSURL(string:"xxxxx.php")
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"

// set Content-Type in HTTP header
let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)

// set data
var dataString = "data=\(data)&engine=\(engine)"
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData

// set content length
//NSURLProtocol.setProperty(requestBodyData.length, forKey: "Content-Length", inRequest: request)

var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)

if let results = NSJSONSerialization.JSONObjectWithData(reply!, options: nil, error: &error) as? [String: String]{
if let name = results["name"]{
labelTestOutput.text = name as? String
}
}

感谢帮助

最佳答案

您可以使用 Alamofire 库来异步,就这么简单:

typealias JSONdic = [String: AnyObject]

let param = ["data": "somedata", "engine": "someEngine"]

Alamofire.request(.POST, URLString: "xxxxx.php", parameters: param).responseJSON() {
(_,_,json,_) in
if let json = json as? JSONdic, name = json["name"] as? String {
// do something with name
}
}

关于php - swift php数组到swift json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32085618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com