【问题标题】:How to prevent alamofire to put "&" sign to front of parameter如何防止alamofire将“&”符号放在参数前面
【发布时间】:2018-08-03 14:57:50
【问题描述】:

我是 Swift 的初学者。我正在尝试使用 PUBG api 创建一个应用程序。我使用 Alamofire 添加我的标题。我的故事板上有一个文本字段,我在那里输入我的昵称并从 pubg api 获取数据。我的问题是 Alamofire 在参数前面添加了“&”符号,所以这会使 url 崩溃。如何防止 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】:

    如果你使用 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
    

    【讨论】:

    • 试过了。它仍然把 & 放在他们前面。
    • 我无法复制这个;请发布您用来证明这一点的代码。我的代码产生:https://api.pubg.com/shards/pc-eu/players?filter%5BplayerNames%5D=PLAYERNAME
    • 好吧,不知何故我得到的链接现在我不知道为什么。也感谢您的回复。
    猜你喜欢
    • 2011-08-06
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 2021-04-06
    相关资源
    最近更新 更多