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

时间:2018-08-03 14:57:50

标签: ios swift alamofire

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

URL应该是这样的:

  

https://api.pubg.com/shards/pc-eu/players?filter%5BplayerNames%5D=PlayerName

相反,它变为:

  

https://api.pubg.com/shards/pc-eu/players?filter%5BplayerNames%5D&=PlayerName

1 个答案:

答案 0 :(得分: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