GET request with parameters

允我心安 提交于 2019-11-28 06:14:50

问题


Which way is recomed in swift 3 for GET with parameters ?

Example :

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

Thanks in advance !


回答1:


Example how to use URLQueryItem for the requests.

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"])



回答2:


Well I'm handling my http requests like this:

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()
    }


来源:https://stackoverflow.com/questions/42696851/get-request-with-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!