0
votes

I am new to Alamofire. One can easily send a POST request using Alamofire. I am stuck with creating JSON parameters for post body. So can somebody inline the best way to create a POST request with request body as JSON paramters.

1

1 Answers

0
votes

Check this one:

let urlAsString1 : String = validateAPI
let urlStr : NSString = urlAsString1.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
let params:NSMutableDictionary? = [
         "Name" : name.text!,
         "PhoneNumber" : Mobile.text!,
         "Type" : selectType,
         ];
let ulr =  NSURL(string:urlStr as String)
let request = NSMutableURLRequest(URL: ulr!)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let data = try! NSJSONSerialization.dataWithJSONObject(params!, options: NSJSONWritingOptions.PrettyPrinted)

let json = NSString(data: data, encoding: NSUTF8StringEncoding)
   if let json = json {
          print(json)
   }
request.HTTPBody = json!.dataUsingEncoding(NSUTF8StringEncoding);


  Alamofire.request(request)
       .responseJSON { response in
            // do whatever you want here
             switch (response.result) {
                case .Success(let JSON):
                        //print("JSON: \(JSON)")
                        break;
                case .Failure:
                        break

                }
            }