2017-04-07 70 views
7

我有一個使用郵遞員傳遞URL參數的工作方案。現在,當我嘗試在Swift中通過Alamofire來完成時,它不起作用。如何添加Alamofire URL參數

您如何在Alamofire中創建此網址? http://localhost:8080/?test=123

_url = "http://localhost:8080/" 
    let parameters: Parameters = [ 
     "test": "123" 
     ] 

    Alamofire.request(_url, 
         method: .post, 
         parameters: parameters, 
         encoding: URLEncoding.default, 
         headers: headers 
+0

只是一句評論:OMG。你知道嗎?我一直在想這個問題,連續3個小時! :'(Pity。 – Glenn

回答

25

的問題是,你使用URLEncoding.default。 Alamofire根據您使用的HTTP method的不同來解釋URLEncoding.default

對於GETHEAD,和DELETE請求,URLEncoding.default編碼參數作爲查詢字符串,並將其添加到URL,但對於任何其他方法(如POST)的參數獲得編碼作爲查詢字符串和發送作爲HTTP請求的主體。

爲了在POST請求中使用查詢字符串,您需要將您的encoding參數更改爲URLEncoding(destination: .queryString)

你可以看到更多關於Alamofire如何處理請求參數here的細節。

您的代碼應該是這樣的:

_url = "http://localhost:8080/" 
    let parameters: Parameters = [ 
     "test": "123" 
     ] 

    Alamofire.request(_url, 
         method: .post, 
         parameters: parameters, 
         encoding: URLEncoding(destination: .queryString), 
         headers: headers) 
+0

非常感謝OP和這個答案,我一直在調試我的代碼3個小時,我一直想知道f出了什麼問題!!!我總是得到狀態500,是想與我的後端開發人員交談,我想通過將參數傳遞給URL來進行測試,然後我意識到Alamofire在編碼時不接受參數JSONEnconding.default。 – Glenn

6

如果你想在查詢字符串中使用的參數,使用.queryString作爲URL編碼,如: (我假設你有地方標題)

let _url = "http://localhost:8080/" 
let parameters: Parameters = [ 
    "test": "123" 
    ] 

Alamofire.request(_url, 
     method: .post, 
     parameters: parameters, 
     encoding: URLEncoding.queryString, 
     headers: headers) 

這種形式是由Alamofire筆者建議,因爲它更coincise給對方,看截圖: Excerpt from website

查看原文here

+0

我相信這是它的工作原理Swift 2,但它在Swift 3中被加入了'JSONEncoding'和'CustomEncoding'。 –

+0

它是最新的使用Swift 3的Alamofire版本。來源:https://github.com/Alamofire/Alamofire#url-encoding –

+0

「目標枚舉有三種情況:...'.queryString' - 將編碼的查詢字符串結果設置或追加到現有的查詢字符串中......」 正如你所看到的,'.queryString '是'Destination'值,而不是'encoding'值。編碼格式爲'URLEncoding(destination:)','JSONEncoding(destination:)'或其他類似的類型。 –