1

Looking on how to make a http get call with query string in Swift2

I can see lots of examples of Objective-c and old versions of swift, but cant find for Swift2

Michael A
  • 5,770
  • 16
  • 75
  • 127

1 Answers1

2

Here is an example that performs a search on the iTunes API:

let timeout = 11 as NSTimeInterval
let searchTerm = "philip+glass"
let url = NSURL(string: "https://itunes.apple.com/search?term=\(searchTerm)")
let request: NSURLRequest = NSURLRequest(URL: url!,
                                        cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData,
                                        timeoutInterval: timeout)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task: NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {
    (data, response, error) in
        if response == nil {
            print("Timeout")
        } else {
            print(String(data: data!, encoding: NSUTF8StringEncoding))
        }
    }
)

task.resume()
Daniel Zhang
  • 5,778
  • 2
  • 23
  • 28
  • Thanks, but say i want to set multiple name value parameters and construct them with appropriate encoding, is there some function which construct those parameters easily? – Michael A Nov 19 '15 at 09:45
  • The answer at https://stackoverflow.com/questions/27723912/swift-get-request-with-parameters has some extensions that will accomplish those things for you. – Daniel Zhang Nov 19 '15 at 09:51