简体   繁体   English

如何使用PHP和Swift 5解析JSON

[英]How to parse JSON with PHP and Swift 5

I'm parsing JSON in my app via PHP, my messaging center was working fine but now it just stopped working. 我正在通过PHP在我的应用程序中解析JSON,我的消息传递中心工作正常,但现在它停止工作了。 I'm using Swift 5, PHP and MySQL. 我正在使用Swift 5,PHP和MySQL。

When I attempt to view the page in the app, I get a JSON error saying, 当我尝试在应用程序中查看页面时,出现JSON错误,

'The data cannot be read because it is not in the right format'. “无法读取数据,因为格式不正确”。

Other pages using the same code are not having this problem. 使用相同代码的其他页面不存在此问题。

I've tried different attributes to JSONSerialization but nothing has worked. 我尝试了JSONSerialization不同属性,但没有任何效果。

Swift 5 code to load messages from php 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 Code 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);

 ?>

The code should display the inbox for the user. 该代码应为用户显示收件箱。

Solved the issue using the following steps: 使用以下步骤解决了该问题:

  1. Printed print(String(data: data!, encoding: .utf8)) 打印的print(String(data:data !, encoding:.utf8))
  2. Error message showed me that my file was being blocked by GoDaddy 错误消息显示我的文件被GoDaddy阻止
  3. Added my page to the whitelist on godaddy's security portal 将我的页面添加到了Godaddy安全门户的白名单中
  4. It worked. 有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM