2016-12-27 115 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 { 
} 
} 

希望這有助於。謝謝。