2017-07-31 54 views
0

如何防止Alamofire編碼(用%5B%5D替換我的方括號)?參數鍵有方括號Alamofire iOS

前段時間我看到有人對此發表評論,但是我找不到問題的鏈接了。我的參數看起來是這樣的:

let parameters: Parameters = [ 
     "xx[firebase_id]" : currentUserId, 
     "xx[lat]"   : latitude, 
     "xx[lng]"   : longitude, 
     "xx[fcm_key]"  : fcmKey 
    ] 

我有,當我的參數是一個集合,將溶液只是刪除括號,像這樣前頗爲相似的問題:從這個

["some_array_param[]" : someCollection]

這個["some_array_param" : someCollection]

所以回到我的簡單問題,我應該只是跟我的後端開發人員談論這個嗎?或者有沒有一種方法可以解決這個問題(無需手動將參數放入url中)?

回答

1

這是我如何通過編碼參數來完成它:

// Remove square brackets for POST request 
let parameterEncoding = ParameterEncoding.Custom { requestConvertible, parameters in 
    let (mutableRequest, error) = ParameterEncoding.URL.encode(requestConvertible, parameters: parameters) 
    let httpBody = NSString(data: mutableRequest.HTTPBody!, encoding: NSUTF8StringEncoding)! 
    mutableRequest.HTTPBody = httpBody.stringByReplacingOccurrencesOfString("%5B%5D=", withString: "=").dataUsingEncoding(NSUTF8StringEncoding) 
    return (mutableRequest, error) 
} 

然後將編碼添加到您的文章:

Alamofire.request(.POST, "http://example.com", parameters: ["foo": ["bar1", "bar2"]], encoding: parameterEncoding) 
+0

真棒。看到這個答案的地方,但有點懷疑嘗試了。現在就試試吧。 :D我會選擇這個作爲答案,如果這對我有用。 – Glenn

+0

您的代碼沒有更新,請嘗試像下面這樣更新:https://stackoverflow.com/a/40546670/3231194,但是,當您發佈此代碼時,您給了我一個嘗試嘗試的想法, ,我已經解決了我需要解決的問題。謝謝你。 – Glenn