Alamofire:POST参数作为Json的POST请求

时间:2016-11-23 06:54:57

标签: swift post alamofire

我是Alamofire的新手。可以使用Alamofire轻松发送POST请求。我坚持为post body创建JSON参数。因此,有人可以使用请求主体作为JSON参数来内联创建POST请求的最佳方法。

1 个答案:

答案 0 :(得分:0)

检查一下:

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

                }
            }