Network

Foundation framework provides a URLSession API to work with network.

URLSession coordinates a group of related, network data transfer tasks. It has a singleton shared session (which doesn’t have a configuration object) for basic requests. Or you can create a URLSession with one of three kinds of configurations:

  • default session behaves much like the shared session, but lets you configure it. You can also assign a delegate to the default session to obtain data incrementally.
  • ephemeral sessions - are similar to shared sessions, but don’t write caches, cookies, or credentials to disk.
  • background sessions - let you perform uploads and downloads of content in the background while your app isn’t running.

There are three main types of session tasks:

  • URLSessionDataTask returns downloaded data directly to the app in memory
  • URLSessionUploadTask uploads data to the network in a request body
  • URLSessionDownloadTask stores downloaded data to a file

URL class represents a URL.

URLComponents class allows to build url from its parts.

URLRequest represents a URL load request that is independent of protocol.

import Network
// ...
let session = URLSession.shared
let url = URL(string: "http://example.com")!

let task = session.dataTask(with: url, completionHandler: { data, response, error in

    // parse json, save to db and etc
    
    DispatchQueue.main.async {
      // update ui if necessary    
    }
})

task.resume() // execute task

You can also use other frameworks like Alamofire and its components (AlamofireImage)

There is also built-in Network framework (IOS12+) to work with network on low-level. It is replacement of Socket API.

build url

var components = URLComponents()
components.scheme = "https"
components.host = "example.com"
components.path = "/some/path"

// create url
let url = components.url

download files

To download files, you create a URLSessionDownloadTask from a URLSession. If you don’t care about receiving progress updates or other delegate callbacks during the download, you can use a completion handler.

Download file

If you want to receive progress updates you must use a delegate. You receive callbacks to your implementations of methods from the URLSessionTaskDelegate and URLSessionDownloadDelegate protocols.

Download file with progress

working with JSON

Post JSON example

download in background

// creating a background URL session
private lazy var urlSession: URLSession = {
    let config = URLSessionConfiguration.background(withIdentifier: "MySession")
    config.isDiscretionary = true // wake up app when a task is completed
    config.sessionSendsLaunchEvents = true // wait for optimal conditions (WI-FI, ...)
    return URLSession(configuration: config, delegate: self, delegateQueue: nil)
}()

// creating a download task from a URL session
let backgroundTask = urlSession.downloadTask(with: url)
backgroundTask.earliestBeginDate = Date().addingTimeInterval(60 * 60)
backgroundTask.countOfBytesClientExpectsToSend = 200
backgroundTask.countOfBytesClientExpectsToReceive = 500 * 1024
backgroundTask.resume()

When app is in the background, the system may suspend your app while the download is performed in another process. To handle this case override application(_:handleEventsForBackgroundURLSession:completionHandler:) method of UIApplicationDelegate. This method receives the session identifier you created ("MySession" in our case) and a completion handler as its final parameter.

Store completion handler wherever it makes sense for your app, perhaps as a property of your app delegate, or of your class that implements URLSessionDownloadDelegate.

// storing the background download completion handler sent to the application delegate
func application(_ application: UIApplication,
                 handleEventsForBackgroundURLSession identifier: String,
                 completionHandler: @escaping () -> Void) {
        backgroundCompletionHandler = completionHandler
}

When all events have been delivered, the system calls the urlSessionDidFinishEvents(forBackgroundURLSession:) method of URLSessionDelegate. At this point, fetch the backgroundCompletionHandler stored by the app delegate and execute it.

// executing the background URL session completion handler on the main queue
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
    DispatchQueue.main.async {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate,
            let backgroundCompletionHandler =
            appDelegate.backgroundCompletionHandler else {
                return
        }
        backgroundCompletionHandler()
    }
}

For more visibility into how the system is scheduling and performing your background tasks, download and install the Background Networking Profile onto your iOS device from the Bug Reporting Profiles and Logs page.