Search code examples
swiftalamofire

API working in Postman but giving error in Code


I am trying to call API in postman and its working fine, But If I am trying to call API in swift Alamofire, Its give me error-

enter image description here

My Code is-

func sendToServer(){
        let urlString = "https://xxxxxxxxxx/TempService/SaveBarCodes"
        
        let data:  Parameters = ["SerialNo": "T8180399","Status":101]
        

        Alamofire.request(urlString, method: .post, parameters: data,encoding: JSONEncoding.default, headers: nil).responseJSON {
        response in
          switch response.result {
                        case .success:
                            print(response)

                            break
                        case .failure(let error):

                            print(error)
                        }
        }
    }

Error is-

The JSON value could not be converted to System.Collections.Generic.List`1[BreakBulkModels.Model.WebapiModels.DtoInventoryApi]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.

Solution

  • Your API accepts as parameters an array of JSON objects but you are currently sending a JSON object:

    {
        "SerialNo": "T8180399",
        "Status": 101
    }
    

    Because Parameters is a typealias to Dictionary<String, Any> (what you need is Array<Dictionary<String, Any>>) you have to do your parameter encoding yourself and then call request(_:) function of Alamofire passing your URLRequest:

    do {
        let urlString = "https://xxxxxxxxxx/TempService/SaveBarCodes"
        let url = try urlString.asURL()
        var request = URLRequest(url: url)
        let data = [["SerialNo": "T8180399", "Status": 101]]
        request = try JSONEncoding.default.encode(request, withJSONObject: data)
        Alamofire.request(request).responseJSON { response in
            switch response.result {
            case .success:
                print(response)
                break
            case .failure(let error):
                print(error)
            }
        }
    } catch {
        print(error)
    }
    

    Edit: With Alamofire v5 there is a more elegant way by using Encodable protocol:

    struct BarCode: Encodable {
        var SerialNo: String
        var Status: Int
    }
    
    func sendToServer(){
        let urlString = "https://xxxxxxxxxx/TempService/SaveBarCodes"
        let data = [BarCode(SerialNo: "T8180399", Status: 101)]
        AF.request(
            urlString,
            method: .post,
            parameters: data,
            encoder: JSONParameterEncoder.default
        ).responseJSON { response in
            switch response.result {
            case .success:
                print(response)
                break
            case .failure(let error):
                print(error)
            }
        }
    }