2016-08-17 26 views
2

我正嘗試在POST API中發送字典。爲此我使用Alamofire。如何使用Alamofire Swift中的數組發送字典

參數字典如下:

var param: Dictionary<String, AnyObject> = 
     [ 
      "name"      : name, 
      "email"     : email, 
      "mobile_number"   : mobile_number, 
      "body"      : body 
      ] as Dictionary<String, AnyObject> 


    param["listing_ids[]"] = [772121,772136,772129] 

發送請求到服務器如下:

Alamofire.request(.POST,baseUrl+enquiryEndPoint , parameters: params , encoding: .URL, headers: createHeader()).responseJSON { response in 
     switch response.result { 
     case .Success: 
      guard let response = response.result.value as? Dictionary<String, AnyObject> else{return} 
      completionBlock(response,error: nil) 
     case .Failure(let error): 
      completionBlock([:],error: error) 
     } 

    } 

時打印參數字典,誤差如下:

["mobile_number": 457823356, "email": [email protected], "body": Hello, I found your property on <country-website>. Please send me additional information about this property. 
Thank you, "listing_ids[]": <_TtCs21_SwiftDeferredNSArray 0x1400d6ff0>(
708783, 
589915, 
722173, 
746261, 
618410 
) 
, "name": s] 

值對應於鍵「listing_ids []」是一個Int數組。這在這裏引起問題。

某些「_TtCs21_SwiftDeferredNSArray」寫在那裏對我來說完全不清楚。

由於我得到空白的迴應。

請幫幫我。

+0

你解決了這個問題嗎? –

+1

@AnandPrem是的我已經解決了這個問題,通過升級Alamofire版本爲SWIFT 3.0 – Sunita

回答

1

在本post提到的可能是你可以嘗試更改編碼爲您的要求

Alamofire.request(.POST,baseUrl+enquiryEndPoint , parameters: params , encoding: .URL, headers: createHeader()).responseJSON { response in 

Alamofire.request(.POST,baseUrl+enquiryEndPoint , parameters: params , encoding: .JSON, headers: createHeader()).responseJSON { response in 

注意它僅僅是方法的編碼參數改變

+0

嗨..我也嘗試過使用.JSON。但API預計.URL編碼。 – Sunita

0

AnyObject只能表示類的類型。在Swift中,Array和Dictionary是結構體,而不是許多其他語言中的類類型。該結構不能被描述爲AnyObject,這就是Any的原因。除了類之外,Any還可以用於所有其他類型,包括struct和enum。

因此,您必須將字典更改爲字典。下面的代碼工作正常,並根據您的要求打印字典。

var param: Dictionary<String, Any> = [ 
      "name"      : "name", 
      "email"     : "email", 
      "mobile_number"   : 123132, 
      "body"      : "Hello" 
      ] 

    param["listing_ids[]"] = [772121,772136,772129] 

    print(param) 
+0

謝謝Aseem ....我已經試過這個解決方案,但正如我所說我使用Alamofire來進行網絡調用,所以Alamofire只接受Dictionary 中的參數。沒有辦法通過字典通過參數。有沒有其他辦法可以解決這個問題? – Sunita

相關問題