How do you start, cancel, suspend, and resume a `URLSessionTask`?

iOS interview question for Intermediate practice.

Answer

To manage URLSessionTask effectively, you need to understand its lifecycle and how to interact with it. Here's a breakdown of how to start, cancel, suspend, and resume a URLSessionTask in Swift: 1. Starting a Task: You start a task by creating a URLSession, configuring the URLRequest, and then creating a URLSessionTask (typically a URLSessionDataTask). You then call the resume() method on the task to initiate the network request. swift let session = URLSession.shared let url = URL(string: "https://www.example.com")! var request = URLRequest(url: url) request.httpMethod = "GET" let task = session.dataTask(with: request) { data, response, error in // Handle the response if let error = error { print("Error: ", error) } else if let data = data { // Process the data print(String(decoding: data, as: UTF8.self)) } } task.resume() 2. Canceling a Task: To cancel a task, call the cancel() method on the URLSessionTask object. This will immediately stop the network request and prevent any further data from being received. The completion handler will still be called, likely with an error. swift task.cancel() 3. Suspending and Resuming a Task: URLSessionTask does not natively provide a suspend or resume method. If you need such functionality, you might use a more advanced technique like URLSessionDownloadTask's cancelByProducingResumeData() method. Using URLSessionDownloadTask for Suspend/Resume (For Downloads): For download tasks, you can suspend a download using cancelByProducingResumeData(). This method returns Data that you can later use to resume the download from where it left off. This is done with resumeData in URLSession.downloadTask(with: resumeData): swift // Suspend Download: let downloadTask = session.downloadTask(with: request) { url, response, error in // Handle the download } downloadTask.cancelByProducingResumeData { data in if let data = data{ //Store this data for later resume } } // Resume Download later if let resumeData = storedResumeData { let resumedTask = session.downloadTask(withResumeData: resumeData) { url, response, error in //Handle the resumed download } resumedTask.resume() } Best Practices: Always handle potential errors in the completion handler. Consider using URLSessionConfiguration to customize the session's behavior (e.g., timeouts, caching). Avoid creating too many URLSession instances; reuse URLSession.shared when appropriate. For long-running tasks, consider using background sessions to prevent interruption. Use proper error handling to manage network issues gracefully. Ensure you appropriately store and manage the resumeData in a persistent way (like UserDefaults or a database), if using suspend/resume functionality. This comprehensive explanation covers the fundamental aspects of managing URLSessionTask effectively in an iOS development context.

Explanation

URLSession's background sessions allow your app to continue downloading data even after the app is closed or suspended by the system.

Related Questions