2016-12-27 112 views
3

我正在使用Swift 3和Alamofire 4.0。发布方法请求Alamofire

我想创建一个类似于Alamofire POST请求,如截图所示邮差要求:

enter image description here

我试着用几行代码:

var parameters: [String: Any] = [ 
    "client_id" : "xxxxxx", 
    "client_secret" : "xxxxx", 
    "device_token" : "xxxx", 
    "fullname" : "xxxxx", 
    "gender": "xxx" 
] 

Alamofire.request(url, method: .post, parameters: parameters).responseJSON { response in 
print(response) 
} 

但我得到这个错误:

enter image description here

如何在Swift 3中使用Alamofire在Body中实现POST请求作为表单数据?

+1

您对响应序列化有麻烦。它是JSON格式吗? –

+0

看看这个错误,它指的是*响应*不是一个有效的JSON,试着先看看响应。 (如使用查尔斯) –

+0

http://stackoverflow.com/questions/31982513/how-to-send-a-post-request-with-body-in-swift –

回答

0
  • 雨燕3.0 - Alamofire - 工作代码,多形式的数据上传*

//参数

let params: [String : String] = 
    ["UserId" : "\(userID)", 
    "FirstName" : firstNameTF.text!, 
    "LastName" : lastNameTF.text!, 
    "Email"  : emailTF.text! 
    ] 

//并上传

Alamofire.upload(
     multipartFormData: { multipartFormData in 

      for (key, value) in params 
      { 
        multipartFormData.append((value.data(using: .utf8))!, withName: key) 
      } 
    }, 
     to: url, 
     encodingCompletion: { encodingResult in 
      switch encodingResult { 
      case .success(let upload, _, _): 
       upload.responseJSON { response in 
        debugPrint(response) 

       } 
       upload.uploadProgress(queue: DispatchQueue(label: "uploadQueue"), closure: { (progress) in 


       }) 

      case .failure(let encodingError): 
       print(encodingError) 
      } 
    } 
    ) 

让我知道你是否仍然有问题。

+0

我是新的Swift编程。 'completionhandler()'是什么意思?我得到一个错误:'使用未解析的标识符'completionhandler',但是源代码在我删除它之后运行良好,并且我从服务器获得了JSON响应。 – user1994

+0

从代码中删除所有completionHandler行 –

+0

这是干什么用的?它只是你的项目中的代码吗? :D – user1994

0

后太多试试我已经succeded所以试试这个

override func viewDidLoad() { 
     super.viewDidLoad() 


     let parameters: Parameters = ["client_id": "1","user_token":"xxxxxxxx"] 
       // Do any additional setup after loading the view, typically from a nib. 
     let url = "http://xxxxxxxxxxx/index.php/Web_api/get_client_profile" 
     //let timeParameter = self.getLastTimeStamp() 
     self.request = Alamofire.request(url, method: .post, parameters:parameters) 
     if let request = request as? DataRequest { 
      request.responseString { response in 
       //PKHUD.sharedHUD.hide() 
       do{ 
        let dictionary = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary 
        print(dictionary) 

       }catch{ 

       } 
      } 
     } 
    } 

    var request: Alamofire.Request? { 
     didSet { 
      //oldValue?.cancel() 
     } 
    } 
0

您可以使用Alamofire发布请求。

let url = "" 
let headers = [ "Content-Type" : "application/json"] 
let para : Parameters = [ "data" : JSONObject] 
Alamofire.request(url, method: .post, parameters: para, encoding: JSONEncoding.default, headers : headers) 
    .responseJSON { response in 

     print(response) 
     print(response.result) 

} 
0

没什么好担心的。 如果你知道如何在Swift 2.0/2.2中做到这一点,那么Alamofire请求方法没有太大的改变(对于Swift 3.0)。如果你了解旧方法,那么你也可以很容易地理解这一点。现在让我们在下面的样板定睛一看 -

Alamofire.request(apiToHit, method: .post, parameters: parametersObject, encoding: JSONEncoding.default, headers: headerForApi).responseJSON { response in switch response.result{ 

    case .success(_): 
     if let receivedData: Any = response.result.value{ 
      if let statusCode: Int = response.response?.statusCode { 
       //Got the status code and data. Do your data pursing task from here. 
      } 
     }else{ 
      //Response data is not valid, So do some other calculations here 
     } 
    case .failure(_): 
      //Api request process failed. Check for errors here. 
    } 

现在,这里在我的情况 -

  1. apiToHit //你的API URL字符串

  2. 。员额//请求的方法。按你需要像。员额,不用彷徨,。放,.delete等需要这种特殊的API

  3. parametersObject //参数可以改变这种方法。同样的情况下,你发送邮递员等“身体”记住这个参数应该是[String: Any]的形式。如果你不需要这个,那么你可以通过nil

  4. JSONEncoding.default //这是编码过程。在我的情况下,我将此设置为.default,这是预期的。如果需要,您也可以将其更改为.prettyPrinted

  5. headerForApi //这是您希望在请求api时发送的标题。在我的情况下,它是在[String: String]格式。如果你不需要这个,那么你可以通过nil

  6. .responseJSON //期望响应如JSON格式。您也可以根据需要进行更改。

现在,在我的请求中,我在请求闭包中使用Switch来检查结果,如response in switch response.result{

里面case .success(_):情况下,我也检查结果数据和http状态代码,以及这样的

if let receivedData: Any = response.result.value{ 
    if let statusCode: Int = response.response?.statusCode { 
} 
} 

希望这有助于。谢谢。