1

I'm parsing JSON in my app via PHP, my messaging center was working fine but now it just stopped working. I'm using Swift 5, PHP and MySQL.

When I attempt to view the page in the app, I get a JSON error saying,

'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.

Swift 5 code to load messages from 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

$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.

8
  • 1
    Check the response data from your PHP server, put print(data! as NSData) before let json : ... and see what's printed. Commented Aug 25, 2019 at 5:35
  • @OOPer I put print commas in and it's printing out a series of number <3c21444f 43545950 45206874 etc Commented Aug 25, 2019 at 5:55
  • 1
    That represents "<!DOCTYPE ht", which may be the first part of the error page. Change the print to print(String(data: data!, encoding: .utf8)) and find what sort of error is happening from the HTML. Commented Aug 25, 2019 at 6:19
  • 1
    It looks like GoDaddy is blocking it as a fake bot page. Commented Aug 25, 2019 at 6:22
  • 2
    You are the one who knows the right solution that solved your own issue. Please write an answer by yourself. Commented Aug 25, 2019 at 7:17

1 Answer 1

1

Solved the issue using the following steps:

  1. Printed print(String(data: data!, encoding: .utf8))
  2. Error message showed me that my file was being blocked by GoDaddy
  3. Added my page to the whitelist on godaddy's security portal
  4. It worked.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.