0

I've been trying to get data by Http "POST" method.In my php script i have a key call "categoryWise" which has a value called "flower".I put all the necessary codes but it doesn't work and says The data couldn’t be read because it isn’t in the correct format.Please help.

    let values = "categoryWise= nature"

    let parameter = values.data(using: .utf8)


    let url = "https://mahadehasancom.000webhostapp.com/WallpaperApp/php_scripts/getImageByCategory.php"

    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "POST"
    request.httpBody = parameter

    request.setValue("application/x-content-type-options", forHTTPHeaderField: "Content-Type")
    request.setValue("application/x-content-type-options", forHTTPHeaderField: "Accept")


    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

        if (error != nil)
        {
            print(error!)
        }
        else
        {
            do
            {
                let fetchData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                //print(fetchData)
                let actorArray = fetchData?["result"] as? NSArray
                for actor in actorArray!
                {
                    let nameDict = actor as? NSDictionary

                    let name = nameDict?["date"] as! String
                    let countryname = nameDict?["category"] as! String
                    let imageUrl = nameDict?["url"] as! String
                    //let pageUrl = nameDict?["url"] as! String

                    authorArray.append(name)
                    titleArray.append(countryname)
                    imageURL.append(imageUrl)
                    //urlArray.append(pageUrl)

                }

                DispatchQueue.main.async {
                    self.CountryNameTable.reloadData()
                }

                print(authorArray)
                print(titleArray)
                print(imageURL)
                print(urlArray)
            }

            catch let Error2
            {
                print(Error2.localizedDescription)

                if let string = String(data: data!, encoding: .utf8)
                {
                    print(string)
                    print(response!)
                }
            }

        }
    }

    task.resume()
Saif Ayon
  • 49
  • 9
  • @Rob Thanks.By printing the string and response i get --> 500 Internal Server Error

    500 Internal Server Error


    nginx
    and { URL: https://mahadehasancom.000webhostapp.com/WallpaperApp/php_scripts/getImageByCategory.php } { status code: 500, headers { "Content-Type" = "text/html"; Date = "Fri, 26 May 2017 20:44:50 GMT"; Server = awex; } } and for key-value, let values = "categoryWise=flower"
    – Saif Ayon May 27 '17 at 04:52
  • @Rob Sorry brother.i actually don't understand the facts about 'request format' and Content-Type as i am new to this kind.Would you please help me solve this.I want to grab all the photos for value "flower" which key is "categoryWise".But i am unable to get the solution.Please help... – Saif Ayon May 27 '17 at 05:00
  • @Rob here is the link for php code.please check & also i've edited my main swift code... https://gist.github.com/saifaion/ebe7082f765c24352c05bd04444c9d41 – Saif Ayon May 27 '17 at 11:04
  • Thanks Man.You are Brilliant.It's solved now. – Saif Ayon May 27 '17 at 17:26

1 Answers1

0

A few observations:

  1. You shared PHP that is using $_POST. That means it's expecting x-www-form-urlencoded request. So, in Swift, you should set Content-Type of the request to be application/x-www-form-urlencoded because that's what you're sending. Likewise, in Swift, the Accept of the request should be application/json because your code will "accept" (or expect) a JSON response.

  2. The values string you've supplied has a space in it. There can be no spaces in the key-value pairs that you send in a x-www-form-urlencoded request. (Note, if you have any non-alphanumeric characters in your values key pairs, you should be percent encoding them.)

  3. In your Swift error handler, in addition to printing the error, you might want to try converting the data to a String, and looking to see what it says, e.g.

    if let string = String(data: data!, encoding: .utf8) {
        print(string)
    }
    
  4. You might also want to look at response and see what statusCode it reported. Having done that, you subsequently told us that it reported a statusCode of 500.

    Status code 500 means that there was some internal error in the web service. (The code is 200 if successful.) This is generally a result of some error with the request not being handled correctly. For example, if the request neglected to format the request correctly and the web service doesn't anticipate/catch that, or if there was some other internal error on the web server, you could get 500 error code. For list of status codes, see http://w3.org/Protocols/rfc2616/rfc2616-sec10.html.

  5. If the text in the body of the response from your web service is not illuminating, you might want to turn on error reporting (see How to get useful error messages in PHP? or How do I catch a PHP Fatal Error) and then look at the body of the response again. For example, you might include the following in your PHP:

    <?php
    
    function __fatalHandler() {
        $error = error_get_last();
        //check if it's a core/fatal error, otherwise it's a normal shutdown
        if ($error !== NULL && in_array($error['type'], array(E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING))) {
            header("Content-Type: application/json");
            $result = Array("success" => false, "error" => $error);
            echo json_encode($result);
            die;
        }
    }
    register_shutdown_function('__fatalHandler');
    // the rest of your PHP here
    ?>
    
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • It's really amazing to get such informations for a beginner from You.I'll try tp keep all these things in my mind.Thanks again for the Suggestions. – Saif Ayon May 27 '17 at 18:06