It turns out that getting some file from the internet is relatively easy with the new NSURLSession API.
A simple example:
brush: swift
let defaultSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
var dataTask: NSURLSessionDataTask?
func fetchData(sender: AnyObject) {
if dataTask != nil { dataTask?.cancel() }
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let url = NSURL(string: "http://localhost:8000/a.json")
dataTask = defaultSession.dataTaskWithURL(url!) {
data, response, error in
dispatch_async(dispatch_get_main_queue()) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
if let error = error {
print(error.localizedDescription)
}
else if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
self.updateData(data)
}
}
}
dataTask?.resume()
}
By the way, it turns out that fetching simple http is no longer the advised way. Only https is accepted out of the box. To allow http for testing, you need to add the following to the Info.plist:
- App Transport Security Settings
- Allow Arbitrary Loads: YES
Based on this article