gpt4 book ai didi

php - SWIFT 和 PHP 与 JSON 交换

转载 作者:可可西里 更新时间:2023-11-01 01:05:28 26 4
gpt4 key购买 nike

iam 使用 swift 函数将 POST 查询发送到 php 脚本

func post_retJSON_inJSON(params : Dictionary<String, String>,tourl:String)
{
let myUrl = NSURL(string: tourl);
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";

var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")


let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{
data, response, error in

if error != nil
{
println("error=\(error)")
return
}

// You can print out response object
println("response = \(response)")

// Print out response body
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")

//Let's convert response sent from a server side script to a NSDictionary object:

var err: NSError?
var myJSON = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:&err) as? NSDictionary

if let parseJSON = myJSON {
// Now we can access value of First Name by its key
var firstNameValue = parseJSON["firstName"] as? String
println("firstNameValue: \(firstNameValue)")
}

UIApplication.sharedApplication().networkActivityIndicatorVisible = false

}

task.resume()
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}

用这个 php

$firstName= $_POST["firstName"];
$lastName = $_POST["lastName"];

$returnValue = array("firstName"=>$firstName, "lastName"=>$lastName);

// Send back request in JSON format
echo json_encode($returnValue);

然后我很快就有了回应

Optional({"firstName":null,"lastName":null})

我想我已经尝试了所有方法,但我无法获取 SWIFT 查询发送的 PHP 参数。请帮我弄清楚!!!

最佳答案

用这个 php 解决了,和 top 一样 swift

// Read request parameters
$postdata = json_decode(file_get_contents("php://input"),TRUE);

$firstName= $postdata["firstName"];
$lastName = $postdata["lastName"];
// Store values in an array
$returnValue = array("firstName"=>$firstName, "lastName"=>$lastName);

// Send back request in JSON format
echo json_encode($returnValue);

关于php - SWIFT 和 PHP 与 JSON 交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31807129/

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