我是Swift的初学者。我正在尝试使用PUBG api创建一个应用程序。我使用Alamofire添加标题。我的故事板上有一个文本字段,我在那里输入我的昵称并从pubg api获取数据。我的问题是Alamofire在参数前加上“&”符号,所以这会破坏网址。如何防止Alamofire为参数添加“&”符号?
let playerURL = "https://api.pubg.com/shards/pc-eu/players?filter[playerNames]"
func findPlayer(playerName:String){
let httpParameters : Parameters = ["":playerName]
Alamofire.request(playerURL,method:.get,parameters:httpParameters,encoding:URLEncoding.default,headers:httpHeaders).responseJSON{response in switch response.result{
case .success(let value):
let response = JSON(value)
print(response["data"])
case .failure(_):
return
}
}
}
网址应如下所示:
https://api.pubg.com/shards/pc-eu/players?filter%5BplayerNames%5D=PlayerName
取而代之的是:
https://api.pubg.com/shards/pc-eu/players?filter%5BplayerNames%5D&=PlayerName
如果您使用Alamofire对参数进行编码,那么您需要让它对参数进行编码:
let playerURL = "https://api.pubg.com/shards/pc-eu/players"
....
let httpParameters : Parameters = ["filter[playerNames]": playerName]
...
我的整个测试用例如下:
let playerURL = "https://api.pubg.com/shards/pc-eu/players"
func findPlayer(playerName:String){
let httpParameters : Parameters = ["filter[playerNames]": playerName]
let request = Alamofire.request(playerURL,
method:.get,
parameters:httpParameters)
print(request)
}
application(_:didFinishLaunchingWithOptions:)
添加:
findPlayer(playerName: "PLAYERNAME")
输出:
GET https://api.pubg.com/shards/pc-eu/players?filter%5BplayerNames%5D=PLAYERNAME