Alamofire get 方法,参数在 url 和 header swift

Alamofire get method with parameters in the url with header swift

我有一个基于 3 个参数的 get 方法 url itself.I 已经尝试了以下代码,但它会失败,说不是有效的 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)
                           
            }
            }
           
        }

您使用 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)
                              
                   }
               }
       }