Network Requests L4.1.1

URLSession refers to network requests as "tasks"

Any task used by URLSession is a subclass of URLSessionTask which has three main tasks

  • Data Task - Returns data from the network directly into memory as "Data" objects. Data tasks are good for short lived requests.
  • Download Task - Returns data from the network into a temporary file.
  • Upload Task - These kinds of tasks are specialized for things like uploading content.

Making a request for an image

It's important to note that the request will only be make if we include task.resume() which kicks things off, but the task will be run in the background. So we add the performUIUpdatesOnMain() to reflect the changes in the UI when the request is finished.

override func viewDidLoad() {  
    super.viewDidLoad()

    let imageURL = URL(string: "https://upload.wikimedia.org/wikipedia/commons/4/4d/Cat_November_2010-1a.jpg")!

    let task = URLSession.shared.dataTask(with: imageURL) { (data, response, error) in

        if error == nil {
            let downloadImage = UIImage(data: data!)

            performUIUpdatesOnMain {
                self.imageView.image = downloadImage
            }
        }
    }

    task.resume()
}

It's recommended that all requests are made over https, but if this is not possible setting the App Transport Settings dict in the info.plist to contain a key value pair Allow Arbitraty Loads => YES will allow http and any other request type. You can make this more specific but this key value pair will allow all request types.