如何防止alamofire将“&”符号放在参数前面

问题描述 投票:-2回答:1

我是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

ios swift alamofire
1个回答
1
投票

如果您使用Alamofire对参数进行编码,那么您需要让它对参数进行编码:

let playerURL = "https://api.pubg.com/shards/pc-eu/players"

....

let httpParameters : Parameters = ["filter[playerNames]": playerName]
...

我的整个测试用例如下:

  • 创建一个空白的单视图项目
  • 在AppDelegate中添加: 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
© www.soinside.com 2019 - 2024. All rights reserved.