0

How do I call this php post request with swift?
I followed many tutorials, but it never worked.

My current try looks like this, but it doesn't work:

 let request = NSMutableURLRequest(url: NSURL(string: "https://example.com/lovetanks/setGabriel.php")! as URL)
        request.httpMethod = "POST"
                let postString = "kiss=\(kiss)&cuddle=\(cuddle)&talk=\(talk)&chat=\(chat)"
        request.httpBody = postString.data(using: .utf8)

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

                    if error != nil {
                        print("error=\(String(describing: error))")
                        return
                    }


                }
                task.resume()

When I just do it with my browser I type:

https://example.com/lovetanks/setName.php?kiss=2&cuddle=1&talk=3.5&chat=7.876

Has any of you an idea?

derGoleb
  • 27
  • 4
  • 2
    What doesn't work? Do you get an error, incorrect data, etc? – George Aug 02 '21 at 20:04
  • 1
    What do response and error say? – El Tomato Aug 02 '21 at 22:00
  • 1
    If you open it with your browser and get results there, it's most likely a GET request, not a POST. – Tamás Sengel Aug 03 '21 at 02:25
  • Completely unrelated (and not the source of your problem), but rather than `let request = NSMutableURLRequest(url: NSURL(string: "https://example.com/lovetanks/setGabriel.php")! as URL)`, do `var request = URLRequest(url: URL(string: "https://example.com/lovetanks/setGabriel.php")!)`. Don’t use those `NS` classes, but rather use the Swift types directly. – Rob Aug 03 '21 at 04:57

1 Answers1

0

If you want to do the equivalent of entering https://example.com/lovetanks/setName.php?kiss=2&cuddle=1&talk=3.5&chat=7.876 in a browser, you would do a GET request, like so:

var components = URLComponents(string: "https://example.com/lovetanks/setName.php")!
components.queryItems = [
    URLQueryItem(name: "kiss", value: "2"),
    URLQueryItem(name: "cuddle", value: "1"),
    URLQueryItem(name: "talk", value: "3.5"),
    URLQueryItem(name: "chat", value: "7.876")
]
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")

let task = URLSession.shared.dataTask(with: components.url!) { data, response, error in
    guard
        let responseData = data,
        let httpResponse = response as? HTTPURLResponse,
        200 ..< 300 ~= httpResponse.statusCode
    else {
        print("error=", String(describing: error), String(describing: response))
        return
    }

    // do something with `responseData` here
}
task.resume()

So, note, because this is a GET request, you don't need URLRequest at all, as you can just use the URL. Also note:

  • I have added some rudimentary error handling (checking not only for fundamental network errors but also HTTP errors that are non 2xx status codes);

  • Rather than building the URL manually, I would suggest using URLComponents (as outlined in https://stackoverflow.com/a/27724627/1271826). For your simple numeric values URLComponents is not strictly needed, but as your URLs get more complicated (e.g. including string values), using URLComponents gets you out of the weeds of manually the encoding of the URL.

  • Also, you did not say whether you were doing this in iOS or macOS. If the latter, remember to go to the “Signing and Capabilities” section of your target settings and enable “App Sandbox” » “Network” » “Outgoing Connections (Client)”.

Rob
  • 415,655
  • 72
  • 787
  • 1,044