0

Hi I'm new to swift and I made following api call o send data but it's not sending and I got following response.

Sent data

firstName=gggg&lastName=ggg&username=fgg&password=ghh&email=ggg@gg.com&latitude=25.0710693470323&longitude=55.143004052641

response

responseString  {"status":"error","message":"Oops!!!Something went wrong..."}

But I can get all other validation messages such as "username cannot be empty".

But I tried with Postman It also gives same error message as above on header methods but later I figured out and sent on Body Method and form of application/x-www-form-urlencoded then I got success response as below.

enter image description here

Following is the My API Call... Please somebody figure out what I am doing wrong or suggest me a better post api call.

One more thing this is the same API call method I made it for "/homefeed" and got the response but we don't need to send any specific parameters for that. Please help me.

 func addNewUser()
    {
        let url = URL(string: "https://xxxxxxxxxx.azurewebsites.net/api/addUser")!

        let firstName:String = firstnameTextFeild.text!
        let lastName:String = lastNameTxtField.text!
        let username:String = usernameTextField.text!
        let password:String = passwordTextField.text!
        let email:String = emailTextField.text!
        var request = URLRequest(url: url)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        let postString = "firstName=\(firstName)&lastName=\(lastName)&username=\(username)&password=\(password)&email=\(email)&latitude=\(lat)&longitude=\(long)"
        print("Sent Data -",postString)
        request.httpBody = postString.data(using: .utf8)
        /*
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body

        } catch let error {
            print(error.localizedDescription)
        }
       */
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(String(describing: error))")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }

            let responseString = String(data: data, encoding: .utf8)

            // print("responseString = \(String(describing: responseString))")
            print("responseString ", responseString ?? "resSt")


        }
        task.resume()

    }
Fido
  • 218
  • 1
  • 17
  • this will help you : https://stackoverflow.com/questions/26364914/http-request-in-swift-with-post-method – Rocky Apr 24 '18 at 06:45
  • @Rocky I'm using the same api call from that post.. I can get the success response for the api's those not have parameters to send. but when i send parameters I'm getting the "something went wrong message" – Fido Apr 24 '18 at 06:50
  • uncomment `JSONSerialization` statement, add `application/x-www-form-urlencoded; charset=utf-8` to `Content-Type`, also add `parameters` variable to your question. – Rocky Apr 24 '18 at 07:13

2 Answers2

1

You should pass your parameters like this:

  let passingDict : [String:Any] = [
                                     "fname" : YourValue,
                                      "lname":YourValue,
                                      "email" : YourValue,
                                      "password" : YourValue,
                                      "countryCode": YourValue,
                                      "mobileNumber": YourValue,
                                      "verificationType":YourValue,

                                     ]

  let signup_url = ApiList.base_url + ApiList.signup_url

  singletonclass.instance.Post_API_Call(passingDict, Url: signup_url, HittingApi: "SIGN_UP_URL")



func Post_API_Call(_ Parame: NSDictionary, Url: String, HittingApi: String)
    {
        var Api_Resp_Err = String()
        var Api_Resp_Dict = NSDictionary()

        do

        {
            let jsonData = try JSONSerialization.data(withJSONObject: Parame, options: [])
            let fullListURL = Url
            let url = URL(string: Url)!

            var request = URLRequest(url: url)

            request.httpMethod = "POST"

            request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

            request.httpBody = jsonData

            let task = URLSession.shared.dataTask(with: request) { data,response,error in

                if error != nil {

                    DispatchQueue.main.async(execute: {

                        Api_Resp_Err = (error?.localizedDescription)!

                    })

                    return
                }
                do
                {
                    if let responseJSON = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
                    {
                        if  responseJSON.count > 0
                        {
                            DispatchQueue.main.async(execute: {

                                let statusCode = responseJSON.object(forKey: "code") as? String ?? ""
                                let message = responseDict.object(forKey: "Message") as? String ?? ""


                            })
                        }
                        else
                        {


                        }
                    }
                    else
                    {
                        DispatchQueue.main.async(execute: {

                            Api_Resp_Err = "Data Issue"

                        })
                    }
                }
                catch
                {
                    DispatchQueue.main.async(execute: {

                        Api_Resp_Err = "Catch Issue"


                    })

                }
            }
            task.resume()
        }
        catch
        {
            DispatchQueue.main.async(execute: {
                //print("Server Issue catch II")
            })
        }

    }
Catherine
  • 654
  • 5
  • 15
1

Use this Code .it' working for you.

install podfile

pod 'Alamofire'

import Alamofire in your ViewController

func addNewUser(){
let url = "your URL"
var param : [String : AnyObject] = [:]

param = ["firstName": firstnameTextFeild.text! as AnyObject,
         "lastName": lastNameTxtField.text! as AnyObject,
         "username": usernameTextField.text! as AnyObject,
         "password": passwordTextField.text! as AnyObject,
         "email": emailTextField.text! as AnyObject,
         "latitude": "your latitude" as AnyObject,
         "longitude": "your longitude" as AnyObject]
print(param)
Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON { (response:DataResponse<Any>) in
    print(response)

    if (response.result.value != nil) {
        //your code
    }
    else{
        //your code
    }
  }
}