statusCode should be 2xx, but is 400 in swift

Viewed 141

I have a login API and use URLSession to hit API but I get the status code 400, here's my code -

 let deviceType = "IOS"
        let deviceToken = "654321"
     @IBAction func onClickLogIn(_ sender: Any) {
            guard let email = self.emailTf.text else {
                return
            }
            guard let password = self.pwdTf.text else {
                return
            }
            let url = URL(string: "http://example/api/login")!
            var request = URLRequest(url: url)
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            request.httpMethod = "POST"
    
            let parameters: [String: Any] = [
                "username": email,
                "password": password,
                "deviceType" : deviceType,
                "deviceToken" : deviceToken
            ]
            request.httpBody = parameters.percentEncoded()
            URLSession.shared.dataTask(with: request) { data, response, error in
                guard let data = data,
                    let response = response as? HTTPURLResponse,
                    error == nil else {
                        print("error", error ?? "Unknown error")
                        return
                }
                
                guard (200 ... 299) ~= response.statusCode else {
                    print("statusCode should be 2xx, but is \(response.statusCode)")
                    print("response = \(response)")
                    return
                }
                do {
                    let json = try JSONSerialization.jsonObject(with: data, options: [])
                    print(json)
                } catch {
                    print(error)
                }
    
                
                let responseString = String(data: data, encoding: .utf8)
                print("responseString = \(String(describing: responseString))")
            }.resume()
            
    
        }

when I use the breakPoints and type PO request.httpBody then it shows nil in httpBody and gets the status code 400 please anyone help me where I make the mistake

2 Answers

Set response data base type:

"application/x-www-form-urlencoded","multipart/form-data","application/json","text/plain","text/xml"

Ask your backend developer about API type ,is it From data api or Raw Json Api.based on that you have to do Coding.

you written for form data

so here is post api with raw json Api implementation

let parameters: [String: AnyObject] = [
    "IdQuiz" : 102,
    "IdUser" : "iosclient",
    "User" : "iosclient",
    "List": [
        [
            "IdQuestion" : 5,
            "IdProposition": 2,
            "Time" : 32
        ],
        [
            "IdQuestion" : 4,
            "IdProposition": 3,
            "Time" : 9
        ]
    ] ]

Alamofire.request(.POST, "http://myserver.com", parameters: parameters, encoding: .JSON)
    .responseJSON { request, response, JSON, error in
        print(response)
        print(JSON)
        print(error)
    }
Related