Swift
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
81: Data Tasks, Download Tasks, Upload Tasks
Look, I've seen this a dozen times in code reviews: a developer uses URLSessionDataTask for every single network request in their app. It works fine during development with small JSON payloads, but the moment the app hits production and tries to pull down a 100MB PDF or a high-res video, the app spikes in memory and the OS kills it. It's a classic trap.
"I can just save the Data object to a file manually"
The misconception is that a dataTask is the universal tool for receiving data, and if you need a file on disk, you just take the Data returned in the completion handler and write it using Data.write(to:).
Here is why that is dangerous. When you use a data task, the entire response is buffered into your device's RAM. If you're downloading a 500MB asset, your app is suddenly claiming 500MB of memory just to hold that blob before you even start writing it to the disk. On an iPhone, that's a great way to get a jetsam event (a memory-related crash). You aren't streaming the data; you're hoarding it.
Matching the Task to the Payload
To do this right, you have to choose the task based on how the data needs to live in memory. I usually break it down into these three scenarios:
- Data Tasks: Use these for "small" things. API calls, JSON responses, or small images. These are meant for requests where the response is intended to be processed immediately in memory.
- Download Tasks: Use these for anything that feels like a "file." These tasks stream the data directly to a temporary file on disk. Your app's memory footprint stays flat, regardless of whether the file is 1MB or 1GB.
- Upload Tasks: Use these when sending files (like a photo or a log file) to a server. Like download tasks, these can be backed by a file on disk so you aren't loading a massive image into a
Dataobject before sending it.
// The "Small Stuff" approach: Data Task
let url = URL(string: "https://api.example.com/user/profile")!
let dataTask = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else { return }
// Perfect for JSON parsing
let profile = try? JSONDecoder().decode(UserProfile.self, from: data)
}
dataTask.resume()
// The "Big Stuff" approach: Download Task
let fileURL = URL(string: "https://assets.example.com/huge-manual.pdf")!
let downloadTask = URLSession.shared.downloadTask(with: fileURL) { localURL, response, error in
// localURL is a path to a temporary file on disk
guard let localURL = localURL else { return }
// You MUST move this file immediately, or the system deletes it
let destinationURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
.appendingPathComponent("manual.pdf")
try? FileManager.default.moveItem(at: localURL, to: destinationURL)
}
downloadTask.resume()
Handling Outbound Data without Memory Spikes
Upload tasks follow a similar logic to download tasks. If you're uploading a user's profile picture, a simple URLRequest with a httpBody (which is a data task) is usually fine. But if you're uploading a 4K video clip, you should use uploadTask(with:fromFile:).
By pointing URLSession to a file URL, the system can stream the bytes from the disk directly to the network interface. I've seen apps lag and stutter because they tried to convert a large video file into a Data object just to put it in a request body. Don't do that. Let the system handle the streaming.
// The professional way to upload a large file
var request = URLRequest(url: URL(string: "https://api.example.com/upload")!)
request.httpMethod = "POST"
let fileURL = URL(fileURLWithPath: "/path/to/video.mp4")
let uploadTask = URLSession.shared.uploadTask(with: request, fromFile: fileURL) { data, response, error in
// Handle server confirmation
}
uploadTask.resume()
📋 Practical Task
Building a High-Resolution Asset Downloader
Your goal is to create a service that downloads a large sample file (you can use any large public PDF or image URL) without loading the entire file into RAM.
Requirements:
- Implement a function
downloadLargeAsset(from url: URL)that usesURLSessionDownloadTask. - Inside the completion handler, implement the logic to move the temporary file from the
localURLprovided by the system to the app'sDocumentsdirectory. - Name the saved file
"downloaded_asset.dat". - Add a print statement that outputs the final destination path of the file so you can verify it exists.
- Ensure you handle the potential error thrown by
FileManager.default.moveItemusing a do-catch block.
There are no comments for now.