1

I have an app in xcode where I will be taking notes and uploading them to a server on the web. I have the following code in xcode to POST. I'm getting an error

 The data couldn’t be read because it isn’t in the correct format.

Here are my parameters to upload to php

 let parameters: [String: Any] = ["title": title, "post": post]

Here is my create Post code

  func createPost(parameters: [String: Any]) {
        guard let url = URL(string: "\(prefixUrl)/post.php") else {
            print("Did not find url")
            return
        }
        
        let data = try! JSONSerialization.data(withJSONObject: parameters)
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = data
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
    
      URLSession.shared.dataTask(with: request ) { (data, res, error) in
            if error != nil {
                print("error", error?.localizedDescription ?? "")
                return
            }
            do {
                if let data = data {
                    let result = try JSONDecoder().decode([postDataBase].self, from: data)
             
                    DispatchQueue.main.sync {
                        print(result)
                    }
                }else {
                    print("No Data")
                }
                
            } catch let JsonError {
                print("fetch json error:", JsonError.localizedDescription)
            }
            
        }.resume()
    }

The create post is wrapped in a class ViewDataBase with other CRUD commands...

I have a struct postDataBase where i know the error The data couldn’t be read because it isn’t in the correct format. could be happening as well. I've changed these to various data types with no success

struct postDataBase: Decodable {
    var ID: String
    var title: String
    var post: String
}

My php code is here. I use bluehost to support my database so i can have a public domain. If you need my username and password let me know i can change it later.

<?php

$connection=mysqli_connect("localhost","****","****");

$ID = $_POST['ID'];
$title = $_POST['title'];
$post = $_POST['post'];
 

    if(!$connection)
    {
        die('Connection Failed');
    }
    else
    {
        $dbconnect = @mysqli_select_db('mlbroadv_PlantAssistDB', $connection);

        if(!$dbconnect)
        {
            die('Could not connect to Database');
        }
        else
        {
            $query = "INSERT INTO Notes (title, post) VALUES ( '$title', '$post');";
            mysqli_query($query, $connection) or die(mysqli_error());

            echo 'Successfully added.';
            echo $query;
        }
    }
?>

My goal is getting my swift data uploaded to php and into mySQL database. There seems to be a disconnect somewhere...

I think the error lies in the following code where the php files is read in to connect with mySQL and to upload my variables...

EDIT:

  let data = try! JSONSerialization.data(withJSONObject: parameters)
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = data
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
    
      URLSession.shared.dataTask(with: request ) { (data, res, error) in

EDIT 2: Still Trying to get it

For this line...

let parameters: [String: Any] = ["title": "Fgh", "post": "Fgg"

I get...

Param raw data is coded as:  ["post": "Fgg", "title": "Fgh"]

For this line...

    let dataParam = try! JSONSerialization.data(withJSONObject: parameters)

I Get...

json serialization request is coded as:  28 bytes

For this line...

    URLSession.shared.dataTask(with: request as URLRequest ) { (data, res, error) in
        if error != nil {
            print("urlsession error is coded as: ", error?.localizedDescription ?? "")
            return
        }

I Get for the data varaible...

urlsession data is coded as:  235 bytes

and for the res variable, I get the following repsonse...

urlsession results is coded as:  <NSHTTPURLResponse: 0x282ea64c0> { URL: https://mlbroadvisions.com/post.php } { Status Code: 200, Headers {
    "Content-Encoding" =     (
        gzip
    );
    "Content-Type" =     (
        "text/html; charset=UTF-8"
    );
    Date =     (
        "Fri, 22 Jul 2022 16:07:03 GMT"
    );
    Server =     (
        cloudflare
    );
    Vary =     (
        "Accept-Encoding"
    );
    "cf-cache-status" =     (
        DYNAMIC
    );
    "cf-ray" =     (
        "72ed6d53f9072be1-ORD"
    );
    "expect-ct" =     (
        "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
    );
    "host-header" =     (
        "c2hhcmVkLmJsdWVob3N0LmNvbQ=="
    );
} }

during the ...

catch let error as NSError {
                   print(error.localizedDescription)

It gives me the error...

The data couldn’t be read because it isn’t in the correct format.
json data is coded as:  235 bytes

What part of my code do i need to change to get it into the correct format i've tried a lot of things none of which worked.

FrosyFeet456
  • 349
  • 2
  • 12
  • 1
    Your swift code sends JSON data to a program called post.php on your server. I don't know PHP very well, but I don't see any code to handle data being sent by a POST from a remote server. You only show mysql code. Where is the code that tries to read the JSON data? – Duncan C Jul 10 '22 at 19:52
  • I added an edit where i think the php file is uploaded and the parameters are read into the php file to connect to mySQL – FrosyFeet456 Jul 10 '22 at 20:45
  • I'd start with `let data = try! JSONSerialization.data(withJSONObject: parameters)` - my guess is that whatever type `post` is, is not serializable. Better error handling there would tell you if my guess is correct. – Jerry Jul 11 '22 at 01:19
  • You are sending plain JSON as a request body. PHP doesn't know what to do with that and will not auto-decode this data into a $_POST array. Try sending regular POST request with form-URL-encoded data just as browsers do. Or, on PHP side - read your data from `php://input` and `json_decode` it. – Jared Jul 11 '22 at 03:31
  • Does this answer your question? [Receive JSON POST with PHP](https://stackoverflow.com/questions/18866571/receive-json-post-with-php) – CBroe Jul 11 '22 at 06:41
  • I'm still trying to get it. In the EDIT 2 I reported as many variables as i could and gettign the same error – FrosyFeet456 Jul 22 '22 at 16:18

0 Answers0