我有一个问题。
如何读取JSON数据并将其显示为UILabel?错误说
“JSON文本没有以数组或对象开头,并且选项允许未设置片段”
我有这些PHP代码提取JSON数据如下:
{"login":"ID0001"}
test.php的
<?php
$connect = mysqli_connect("","","","");
global $connect;
if(isset($_POST['login'])) {
$login = $_POST['login'];
$sql = "SELECT * FROM table WHERE login='$login'";
$result = mysqli_query($connect, $sql);
if($result && mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)){
$login_db = $row['login'];
$output = array ('login'=>$login_db);
}
print (json_encode($output));
mysqli_free_result($result);
}
else {
echo "No data found!";
echo mysqli_error($connect);
}
}
else {
echo "No input";
}
?>
但在x代码中,我无法打印JSON数据,无法在UILabel _loginLbl 上显示它。有人可以帮我解决这个问题吗?
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBOutlet var _login: UITextField!
@IBOutlet var _loginLbl: UILabel!
@IBOutlet var sendButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func sendData(_ sender: Any) {
let login = _login.text
if(login == "") {
print("No value entered")
return
}
let postString = "login=\(login)"
print("JSON value =\(postString)")
let url = URL(string: "http://localhost/get.php")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else {
self._loginLbl.text = "Error data"
print("Error result =\(error)")
return
}
do {
print("Value here")
if let json = try JSONSerialization.jsonObject(with: data) as? [String: String] {
DispatchQueue.main.async {
let loginvalue = json["login"]
self._loginLbl.text = loginvalue;
print(json)
}
}
}
catch let parseError
{
print("Catch error: \(parseError)")
self._loginLbl.text = "Catch error";
let responseString = String(data: data, encoding: .utf8)
print("response :\(responseString)")
}
}
task.resume()
}
}
感谢。