ATCraiger
ATCraiger

Reputation: 139

How to pass form-urlencoded data in GET request with SWIFT 5

I'm using Swift 5 and attempting to get an access token from an API I'm developing using asp.net MVC. With Postman I set my request to GET, pass in some information in the body, and I get back an access token.

In XCode when I try this it gives me the error: "GET method must not have a body."

My Code:

func GetToken(email: String, password: String) {
        let dataToSend = [
            "grant_type": "password",
            "username": email,
            "password": password
        ]

        let newData = try! JSONSerialization.data(withJSONObject: dataToSend, options: [])

        var request = URLRequest(url: getNewTokenURL)
        request.httpMethod = "Get"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = newData

        URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard let data = data else {return}

            do {
                let myData = try JSONDecoder().decode(TokenResponse.self, from: data)

                self.userToken = myData.accessToken

            }
            catch {

            }
        }.resume()
    }

How do I perform the GET request with the data I need to send to it?

Upvotes: 0

Views: 301

Answers (1)

Frankenstein
Frankenstein

Reputation: 16341

GET requests don't have a body. Parameters in a GET request are passed along with it's url as query parameters.

let url = URL(string: "https://www.example.com/getExample?sampleParam=sampleValue&anotherParam=anotherValue")

Edit: Also you need to give method in all caps. Since GET is the default you didn't have an issue.

Also if you are sure that the data is being passed as JSON then the method should be a POST method for that you just need to set the method of the request to POST as follows:

request.method = "POST"

Note: It's case sensitive.

Upvotes: 1

Related Questions