【问题标题】:Alamofire get method with parameters in the url with header swiftAlamofire get 方法在带有标头的 url 中带有参数 swift
【发布时间】:2020-12-03 14:41:38
【问题描述】:

我在基本 url 本身上有一个带有 3 个参数的 get 方法。我已经尝试了以下代码,但它会失败,说明不是有效的 url 或不是有效的 JSON。 解决这个问题的正确方法是什么? 我使用的代码如下:

 let header: HTTPHeaders = ["Content-Type":"application/json","x-token":self.token!]
        
        
        let todosEndpoint: String = "https://reachwebdemo.com/2020/10/listcribdev/api/chatnotification?" + "channel_sid=\(self.channelsid!)&author=\(self.userid!)&message=\(inputMessage)"
        if let encoded = todosEndpoint.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),let url = URL(string: encoded)
         {
            print("notify url is",url)
            AF.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: header).responseString { response in
                
                switch response.result {
                                  case .success(let json):
                                      print("Validation Successful for push notification",json)
                                
                case let .failure(error):
                    print("error for push notificaton",error.errorDescription)
                           
            }
            }
           
        }

【问题讨论】:

  • 测试哪个无效。与其不知道是哪一个失败,不如分两次做:如果let encoded = ... { if let url = ... { } else { print("url is invalid") } } else { print("encoded is nil") }
  • 好的,我会检查一下
  • 但是,Alamofire 应该为你做这一切。您需要提供参数:["channel_sid": self.channelsid, "author": self.userid, "message: inputMessage]。而不是自己构建网址。见github.com/Alamofire/Alamofire/blob/master/Documentation/…
  • 但这是get方法而不是post方法
  • 往前滚动一点。锚链接乱了。

标签: swift parameters get alamofire


【解决方案1】:

您的用户参数(如 url)和这样的请求方式是错误的。 您需要在请求方法上添加参数,如参数。是的,您可以在“GET”请求中使用参数。

    let header: HTTPHeaders = ["Content-Type":"application/json","x-token":self.token!]
    let todosEndpoint: String = "https://reachwebdemo.com/2020/10/listcribdev/api/chatnotification"
    let params:[String: Any] = ["channel_sid":self.channelsid!, "author":self.userid!, "message": inputMessage]
    
    if let encoded = todosEndpoint.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
       let url = URL(string: encoded) {
               print("notify url is",url)
               AF.request(url, method: .get, parameters: params, encoding: URLEncoding.default, headers: header).responseString { response in
                   switch response.result {
                   case .success(let json):
                       print("Validation Successful for push notification",json)
                   case let .failure(error):
                       print("error for push notificaton",error.errorDescription)
                              
                   }
               }
       }

【讨论】:

  • 感谢大家的回答。两人都很有帮助
猜你喜欢
  • 1970-01-01
  • 2023-04-07
  • 2018-11-25
  • 2017-03-02
  • 1970-01-01
  • 1970-01-01
  • 2018-05-25
  • 2013-12-22
  • 1970-01-01
相关资源
最近更新 更多