A list,

Starting with iOS7, apple introduced URLSession, called NSURLSession in OC, instead of URLConnection. Since the underlying layer of Alamofire is also a encapsulated URLSession, let’s first understand the native URLSession, and then learn Alamofire more thoroughly. If you already have a good grasp of URLSession, you can skip this article.

URLSession request

1. Basic process of request

Configurations ➡️ Creates a session ➡️ creates a task ➡️ Resume () Starts asking ➡️ to listen for callbacks

URLSession.shared.dataTask(with: url) { (data, response, error) in
    if error == nil {
        print("Request successful"\(String(describing: response))" )
    }
}.resume()
Copy the code

The above is a basic request format for URLSession, where urlsession.shared provides us with a singleton session object that provides the default configuration for creating tasks. Configurations are omitted, and the above code can be expanded in detail as follows:

let configure = URLSessionConfiguration.default
let session = URLSession.init(configuration: configure)
session.dataTask(with: url) { (data, response, error) in
    if error == nil {
        print("Request successful"\(String(describing: response))" )
    }
}.resume()
Copy the code

URLSession Instances can be created using the URLSessionConfiguration. Why is it possible to omit configure in the first part of the code?

URLSessionConfiguration:

The reason is that there are three types of configure:

  • .default: is the default value, which is the same as the session created by urlsession.shared, but can be extended more than this singleton.
  • .ephemeral: ephemeralURLSession.sharedIt’s very similar, except it doesn’t writecaches, cookiescredentials(Certificate) to disk.
  • Background: background session, which can be uploaded and downloaded when the program cuts to the background, crashes, or does not run.

URLSessionTask:

URLSessionTask is an abstract class that represents a task object. A session creates a task. Tasks here refer to fetching data, downloading or uploading files. There are four types of tasks:

  • URLSessionDataTask: Handles getting data from the server into memory from HTTP GET requests.
  • URLSessionUploadTask: uploads a file from a hard disk to the server in HTTP POST or PUT mode
  • URLSessionDownloadTask: Downloads a file from a remote server to a temporary file location.
  • NSURLSessionStreamTask: A stream-based URL session task that provides a TCP/IP connection interface created through NSURLSession.

Task operation

Note: Our network task is suspend by default, and you need to use the resume() function after retrieving the dataTask to resume or start the request.

  • resume(): Start a task
  • suspend(): Pause a task
  • cancel(): Cancel the task

2. Background download

Since the introduction of URLSession, iOS has really implemented background downloads. Below is a simple background download implementation.

1. Initialize the configuration of a background mode

let configuration = URLSessionConfiguration.background(withIdentifier: self.createID())
Copy the code

2. Initialize the network download session through configuration, set the related proxy, and call back the data signal response.

let session = URLSession.init(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
Copy the code

3. Session Creates a downloadTask. – Resume starts

session.downloadTask(with: url).resume()
Copy the code

4. Initiate a connection – send a related request – callback proxy response

  • Download the progress of the agent callback urlSession (_ session: downloadTask: didWriteData bytesWritten: totalBytesWritten: totalBytesExpectedToWrite: ) to monitor download progress:
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    print(" bytesWritten \(bytesWritten)\n totalBytesWritten \(totalBytesWritten)\n totalBytesExpectedToWrite \(totalBytesExpectedToWrite)")
    print("Download progress:\(Double(totalBytesWritten)/Double(totalBytesExpectedToWrite))\n")}Copy the code

Due to HTTP shard transport, download progress is called back at regular intervals.

  • The didFinishDownloadingTo agent callback transfers the data in the temporary file to the appropriate sandbox after downloading
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    // Download complete - Start sandbox migration
    print("Download complete -\(location)")
    let locationPath = location.path
    // Copy to user directory (filename named after timestamp)
    let documnets = NSHomeDirectory() + "/Documents/" + self.lgCurrentDataTurnString() + ".mp4"
    print("Mobile address:\(documnets)")
    // Create file manager
    let fileManager = FileManager.default
    try! fileManager.moveItem(atPath: locationPath, toPath: documnets)
}
Copy the code

5. Enable background download permission

In addition to these, want to realize the background download must also be implemented in the AppDelegate handleEventsForBackgroundURLSession, open the background download permissions:

class AppDelegate: UIResponder.UIApplicationDelegate {
    var window: UIWindow?
    // Used to save the completionHandler for the background download
    var backgroundSessionCompletionHandler: (() -> Void)?
    func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping (a) -> Void) {
        self.backgroundSessionCompletionHandler = completionHandler
    }
}
Copy the code

6, in urlSessionDidFinishEvents callback system callback

You also need to call the system callback in the main thread to tell the system to update the screen in time

func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
    print("Background task download back")
    DispatchQueue.main.async {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate.let backgroundHandle = appDelegate.backgroundSessionCompletionHandler else { return }
        backgroundHandle()
    }
}
Copy the code

⚠️ If you do not implement the callback function in the agent, you can still implement the background download, but there will be a lag problem, the console will also appear warning.

Warning: Application delegate received call to – application:handleEventsForBackgroundURLSession:completionHandler: but the completion handler was never called.

So much for the basics of URLSession, let’s take a look at Alamofire in the next article!

The above summary refers to and partly extracts the following articles, thanks very much to the following authors for sharing! :

1. “Basic Use of URLSession” by Shengzhi _HY

2. Alamofire- essential skills of URLSession by Cooci

Reprint please note the original source, shall not be used for commercial communication – any more