嘿你好我的代码有问题我有3天这个问题,我不能自己解决。谁想要帮助我的项目,您可以留下您的联系人。我会联系你。
这是我的PHP代码
<?php
// Create connection
$conn = @mysqli_connect('localhost', 'id2066022_oakkozht', 'oakko7596');
mysqli_select_db($conn, "id2066022_uficondb") or die ("no database");
date_default_timezone_set('Asia/Bangkok');
$timestamp = date('Y-m-d H:i:s');
$numQue=$_POST["numQue"];
$dated=$_POST["dated"];
$return_arr = array();
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$insertation = "INSERT INTO uficontable (date_timestamp)
VALUES (CURRENT_TIMESTAMP)";
$selectation = "SELECT * FROM uficontable ORDER BY id DESC LIMIT 1";
$insertationQuery = mysqli_query($conn, $insertation);
if (!$insertationQuery) {
echo "Could not process your information " . mysqli_error();
} else {
$selectationQuery = mysqli_query($conn, $selectation);
while ($data = mysqli_fetch_assoc($selectationQuery))
{
$return_arr[] = $data;
}
}
echo json_encode($return_arr);
echo "Connected successfully";
?>
和SWIFT
func requestPost () {
let request = NSMutableURLRequest(url: NSURL(string: "https://oakkohost.000webhostapp.com/test.php") as! URL)
request.httpMethod = "POST"
let postString = "numQue"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
let responseString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
print("post: \(responseString)")
}
task.resume()
}}
结果是
[{&#34; id&#34;:&#34; 147&#34;,&#34; date_timestamp&#34;:&#34; 2017-06-26 16:42:16&#34;} ]
问题是我想使用这个结果,我的标签在Swift Code中的ID我怎么能用它?
感谢您的回答
答案 0 :(得分:2)
您需要做的是使用JSONSerialization
从JSON
获取data
个对象。同样在Swift 3中,使用URLRequest
和URL
代替NSMutableURLRequest
和NSURL
。
func requestPost () {
var request = URLRequest(url: URL(string: "https://oakkohost.000webhostapp.com/test.php")!)
request.httpMethod = "POST"
let postString = "numQue"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
if let array = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [[String:Any]],
let obj = array.first {
let id = obj["id"] as? String
//Set id to label on main thread
DispatchQueue.main.async {
self.yourIdLabel.text = id
}
}
}
task.resume()
}
答案 1 :(得分:0)
var json: [Any]?
do {
// Get json from data
json = try JSONSerialization.jsonObject(with: data) as? [Any]
} catch {
print(error)
}
// Get item from json object
guard let item = json?.first as? [String: Any],
let id = item["id"] as? [String: Any] else {
return
}
// Assign the `id` to your label
yourLabel.text = id