一尘不染

带有参数的GET请求

swift

在swift 3中建议使用带参数的GET的哪种方法?

范例:

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

提前致谢 !


阅读 779

收藏
2020-07-07

共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"])
2020-07-07