Search code examples
iospostmethodsalamofire

how to post id and password by alamofire


all. I study iOS and alamofire.

I tried to connect Login API url. It is correctly operating.

this is code.

var rTest = Alamofire.request(self.authLoginUrl, method: .post)
            .responseJSON{ response in
                print(response.request)  // original URL request
                print(response.response) // URL response
                print(response.data)     // server data
                print(response.result)   // result of response serialization

                if let JSON = response.result.value {
                    print("JSON: \(JSON)")
                }
        }

    }

and i want to post id and password

let params = ["Username": "ryulstory", "Password": "1234!"]
        var rTest = Alamofire.request(self.authLoginUrl, method: .post, Parameters: params)
            .responseJSON{ response in
                print(response.request)  // original URL request
                print(response.response) // URL response
                print(response.data)     // server data
                print(response.result)   // result of response serialization

                if let JSON = response.result.value {
                    print("JSON: \(JSON)")
                }
        }

    }

there are error :Extra argument 'method' in call. the error doesn't show if i don't put params. what is problem? could you help me?

best regards.


Solution

  • Assuming your backend receives and returns JSON, this should work

    let params: Parameters = [
        "Username": "ryulstory", 
        "Password": "1234!"
    ]
    
    //if server accepts and returns JSON
    Alamofire.request(self.authLoginUrl, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).validate().validate(contentType: ["application/json"])
                .responseJSON() { response in
                    switch response.result {
    
                    case .success:
                        print("Success")
                    case .failure(let error):
                          print("Failure")
                    }
                }
                .response { response in
                    log.debug("Request: \(String(describing: response.request))")
                    log.debug("Response: \(String(describing: response.response))")
                    log.debug("Error: \(String(describing: response.error))")
    
                    if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                        log.debug("Data: \(utf8Text)")
                    }
            }