【问题标题】:GET request with parameters带参数的 GET 请求
【发布时间】:2017-03-09 13:37:07
【问题描述】:

在 swift 3 中,对于带参数的 GET 推荐哪种方式?

例子:

https://my-side.com/data?token=AS7F87SAD84889AD/

提前致谢!

【问题讨论】:

  • NSURLQueryItem.

标签: swift swift3 nsurlsession


【解决方案1】:

示例如何将URLQueryItem 用于请求。

func getRequest(params: [String:String]) {

    let urlComp = NSURLComponents(string: "https://my-side.com/data")!

    var items = [URLQueryItem]()

    for (key,value) in params {
        items.append(URLQueryItem(name: key, value: value))
    }

    items = items.filter{!$0.name.isEmpty}

    if !items.isEmpty {
      urlComp.queryItems = items
    }

    var urlRequest = URLRequest(url: urlComp.url!)
    urlRequest.httpMethod = "GET"
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
    })
    task.resume()
}


getRequest(params: ["token": "AS7F87SAD84889AD"])

【讨论】:

  • 如果我没记错的话,如果items 为空(无参数),它将添加一个“?”在 URL 上,这可能会导致 404。只有当 items 不为空时,urlComp.queryItems = items 也是如此,不是吗?
  • 嗨 @OlegGordiichuk 我将在哪个页面上调用 getRequest(params: ["token": "AS7F87SAD84889AD"]) ?
【解决方案2】:

我正在像这样处理我的 http 请求:

func getData(completionHandler: @escaping ((result:Bool)) -> ()) {

        // Asynchronous Http call to your api url, using NSURLSession:
        guard let url = URL(string: "https://my-side.com/data?token=AS7F87SAD84889AD/") else {
            print("Url conversion issue.")
            return
        }

        var request = URLRequest(url: url)

        request.httpMethod = "GET"

        URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
            // Check if data was received successfully
            if error == nil && data != nil {
                do {
                    // Convert NSData to Dictionary where keys are of type String, and values are of any type
                    let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:AnyObject]

                    //do your stuff

                    completionHandler(true)

                } catch {
                    completionHandler(false)
                }
            }
            else if error != nil
            {
                completionHandler(false)
            }
        }).resume()
    }

【讨论】:

  • 如何在请求中添加参数?
  • url包含参数。
  • 这有点不正确,因为它不灵活,只是硬编码
  • @OlegGordiichuk 你是对的,每次输入后令牌都会改变。但这并不意味着它不是一种方法——不是最好的,而是一些。谢谢你们两位的帮助!
猜你喜欢
  • 1970-01-01
  • 2015-02-03
  • 2015-02-27
  • 1970-01-01
  • 2014-02-15
  • 2023-04-07
  • 2019-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多