![](/img/trans.png)
[英]How to Parse a JSON with Swift on IOS, sent from a PHP service script?
[英]How to parse JSON with PHP and Swift 5
我正在通過PHP在我的應用程序中解析JSON,我的消息傳遞中心工作正常,但現在它停止工作了。 我正在使用Swift 5,PHP和MySQL。
當我嘗試在應用程序中查看頁面時,出現JSON錯誤,
“無法讀取數據,因為格式不正確”。
使用相同代碼的其他頁面不存在此問題。
我嘗試了JSONSerialization
不同屬性,但沒有任何效果。
Swift 5代碼從php加載消息
func loadMessages() {
let username = user!["username"] as! String
let url = URL(string: "https://www.xxxx.com/messagecenter.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let body = "username=\(username)"
request.httpBody = body.data(using: String.Encoding.utf8)
URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async(execute: {
if error == nil {
do {
let json : NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
self.tableView.reloadData()
guard let parseJSON = json else {
print("Error while parsing")
return
}
guard let messages = parseJSON["messages"] as? [AnyObject] else {
print("Error while parseJSONing")
return
}
self.hhmessages = messages
for i in 0 ..< self.hhmessages.count {
let path = self.hhmessages[i]["ava"] as? String
if !path!.isEmpty {
let url = URL(string: path!)!
let imageData = try? Data(contentsOf: url)
let image = UIImage(data: imageData!)!
self.avas.append(image) // append found image to [images] var
} else {
let image = UIImage()
self.avas.append(image)
}
}
self.tableView.reloadData()
} catch {
Helper().showAlert(title: "JSON Error", message: error.localizedDescription, in: self)
return
}
} else {
}
})
}.resume()
}
PHP代碼
$access->connect();
$returnArray = array();
if (!empty($_REQUEST["uuid"]) && empty($_REQUEST["id"])) {
// STEP 2.1 Get uuid of post and path to post picture passed to this php file via swift POST
$uuid = htmlentities($_REQUEST["uuid"]);
//$path = htmlentities($_REQUEST["path"]);
// STEP 2.2 Delete post according to uuid
$result = $access->deleteMessage($uuid);
if (!empty($result)) {
$returnArray["message"] = "Successfully deleted";
$returnArray["result"] = $result;
} else {
$returnArray["message"] = "Could not delete post";
}
}
else {
// STEP 2.1 Pass POST / GET via html encrypt and assign passed id of user to $id var
$username = htmlentities($_REQUEST["username"]);
// STEP 2.2 Select posts + user related to $id
$messages = $access->messageCenter($username);
// STEP 2.3 If posts are found, append them to $returnArray
if ($messages) {
$returnArray['messages'] = $messages;
}
}
// STEP 3. Close connection
$access->disconnect();
// STEP 4. Feedback information
echo json_encode($returnArray);
?>
該代碼應為用戶顯示收件箱。
使用以下步驟解決了該問題:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.