Search code examples
iosswiftpostman

Post parameters not reaching API from app


I have a PHP API for login which accepts parameters - login_id, password, imei_no, and returns validation result as response. I am facing an issue in sending the request to API in iOS (Swift). The API receives blank parameters. I have run the API on Postman with the same parameters and it works fine.

Please help me find the error in the code.

let parameters = ["login Id": "guest", "password": "guest123", "imei_no": 123456] as [String : Any]
    print(parameters)


    let request = NSMutableURLRequest(url: NSURL(string: "http://xxxxxxxxxxxxxxxxxxxxxxx/Appwebservice/loginAuth")! as URL,
                                      cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
    request.httpMethod = "POST"
    request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
    let dataExample: Data = NSKeyedArchiver.archivedData(withRootObject: parameters)
    request.httpBody = dataExample as Data

    let session = URLSession.shared
    let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
        if (error != nil) {
            print(error)
        } else {
            let httpResponse = response as? HTTPURLResponse
            print(httpResponse)
        }
    })

    dataTask.resume()

}

I have tried the request code given by postman also. Still the parameters appear blank in the API


Solution

  • Since you are sneding no files, you shouldn't use multipart/form-data. It's much more complicated than application/x-www-form-urlencoded.

    You have to encode your parameters and not to archive them. You can do this like that:

    let parameterArray = parameters.map { (key, value) -> String in
        return "\(key)=\(value.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed))"
    }
    let parametersString = parameterArray.joinWithSeparator("&")
    let dataExample = parametersString.data(using: .utf8)
    

    Use this dataExample instead that of your code.