2017-03-09 272 views
2

在swift 3中使用參數GET的方法是什麼?帶參數的GET請求

例子:

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

提前感謝!

+3

'NSURLQueryItem'。 – Larme

回答

6

示例如何使用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"]) 
+2

如果我沒有記錯,如果'items'是空的(沒有參數),它會添加一個「?」在URL上,這可能會導致404.所以'urlComp.queryItems =項目'只有'items'不是空的,不是? – Larme

+0

@Larme你是對的。立即修復代碼。 –

1

嗯,我處理我的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() 
    } 
+0

如何將PARAMS添加到請求中? –

+0

url包含參數。 – Kingalione

+1

這是一個不正確的行爲,因爲它不靈活,但只是硬編碼 –