URLSession helps your app talk to the internet. It lets you get or send data from websites or servers.
When you want to download information like weather or news from the internet.
When you need to send data to a server, like uploading a photo or sending a message.
When your app needs to load images or files from a website.
When you want to connect to an online service to get user data.
When you want to update your app content without updating the app itself.
Syntax
iOS Swift
let session = URLSession.shared
let url = URL(string: "https://example.com")!
session.dataTask(with: url) { data, response, error in
// handle the response here
}.resume()
URLSession.shared is a shared session you can use for simple tasks.
The dataTask method starts a task to get data from the URL.
Examples
This example fetches data from a URL and prints how many bytes were received.
iOS Swift
let url = URL(string: "https://api.example.com/data")!
URLSession.shared.dataTask(with: url) { data, response, error inif let data = data {
print("Data received: \(data.count) bytes")
}
}.resume()
This example downloads an image and sets it to an image view on the main thread.
iOS Swift
let url = URL(string: "https://example.com/image.png")!
URLSession.shared.dataTask(with: url) { data, response, error inif let data = data {
DispatchQueue.main.async {
imageView.image = UIImage(data: data)
}
}
}.resume()
Sample App
This app shows how to use URLSession to fetch JSON data from the internet and display it in a label.
iOS Swift
import UIKit
class ViewController: UIViewController {
let label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
label.frame = CGRect(x: 20, y: 100, width: 300, height: 50)
label.textColor = .black
view.addSubview(label)
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")!
URLSession.shared.dataTask(with: url) { data, response, error inif let data = data, let text = String(data: data, encoding: .utf8) {
DispatchQueue.main.async {
self.label.text = text
}
} else {
DispatchQueue.main.async {
self.label.text = "Failed to load data"
}
}
}.resume()
}
}
OutputSuccess
Important Notes
Always call resume() to start the data task.
Network calls happen in the background, so update UI on the main thread.
Check for errors and handle them to avoid crashes.
Summary
URLSession lets your app communicate with the internet easily.
Use dataTask to download or upload data asynchronously.
Always update your app's UI on the main thread after getting data.
Practice
(1/5)
1. What is the main purpose of URLSession in Swift?
easy
A. To create user interface elements
B. To handle network requests and communicate with the internet
C. To manage local file storage
D. To perform mathematical calculations
Solution
Step 1: Understand URLSession role
URLSession is designed to manage network tasks like downloading or uploading data.
Step 2: Compare with other options
Creating UI, managing files, or math are unrelated to URLSession.
Final Answer:
To handle network requests and communicate with the internet -> Option B
Quick Check:
URLSession = network communication [OK]
Hint: Remember URLSession is for internet tasks only [OK]
Common Mistakes:
Confusing URLSession with UI components
Thinking URLSession manages local files
Assuming URLSession does math operations
2. Which of the following is the correct way to create a data task with URLSession?
easy
A. let task = URLSession.dataTask(url) { data, error in }
B. let task = URLSession.shared.dataTask(url)
C. let task = URLSession.shared.downloadTask(url)
D. let task = URLSession.shared.dataTask(with: url) { data, response, error in }
Solution
Step 1: Check correct method signature
The correct method is dataTask(with:completionHandler:) on URLSession.shared.
Step 2: Validate options
let task = URLSession.shared.dataTask(with: url) { data, response, error in } matches the correct syntax with closure parameters data, response, error. Others have wrong method names or missing parameters.
Final Answer:
let task = URLSession.shared.dataTask(with: url) { data, response, error in } -> Option D
Quick Check:
Correct dataTask syntax = let task = URLSession.shared.dataTask(with: url) { data, response, error in } [OK]
Hint: Look for shared session and closure with three parameters [OK]
Common Mistakes:
Using dataTask without shared session
Missing response parameter in closure
Using downloadTask instead of dataTask
3. What will the following code print if the network request succeeds and returns data?
let url = URL(string: "https://example.com")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
print("Data received: \(data.count) bytes")
} else {
print("No data")
}
}
task.resume()
medium
A. Data received: [number] bytes
B. Syntax error
C. No data
D. Data received: 0 bytes
Solution
Step 1: Analyze dataTask completion handler
If the request succeeds, data contains the downloaded bytes, so data.count is a positive number.
Step 2: Check print statements
The code prints "Data received: \(data.count) bytes" if data exists, otherwise "No data".
Final Answer:
Data received: [number] bytes -> Option A
Quick Check:
Successful dataTask prints data size [OK]
Hint: If data exists, print shows byte count, not zero [OK]
Common Mistakes:
Assuming data is always nil
Confusing data.count with zero
Thinking code has syntax errors
4. Identify the error in this code snippet:
let url = URL(string: "https://example.com")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
DispatchQueue.main.async {
print("Data length: \(data.count)")
}
}
}
// Missing task.resume()
medium
A. Missing call to task.resume() to start the request
B. Incorrect URL string format
C. DispatchQueue.main.async should not be used here
D. Closure parameters are incorrect
Solution
Step 1: Check for starting the task
URLSession tasks are created suspended. You must call task.resume() to start the network request.
Step 2: Validate other parts
URL string is valid, closure parameters are correct, and updating UI on main thread is good practice.
Final Answer:
Missing call to task.resume() to start the request -> Option A
Quick Check:
Always call resume() to run URLSession tasks [OK]
Hint: Remember to call resume() after creating a data task [OK]
Common Mistakes:
Forgetting to call task.resume()
Misusing DispatchQueue for UI updates
Incorrect closure parameters
5. You want to fetch JSON data from a URL and update a label with the result. Which approach correctly ensures the UI updates happen on the main thread?
let url = URL(string: "https://api.example.com/data")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else { return }
let text = String(data: data, encoding: .utf8) ?? "No data"
// Update label here
}
task.resume()
Options:
hard
A. Call label.text = text before task.resume()
B. Update label.text directly inside the closure without DispatchQueue
C. Use DispatchQueue.main.async { label.text = text } inside the closure
D. Use a background thread to update label.text
Solution
Step 1: Understand threading in URLSession
The completion handler runs on a background thread, so UI updates must be dispatched to the main thread.
Step 2: Check each option
Use DispatchQueue.main.async { label.text = text } inside the closure correctly uses DispatchQueue.main.async to update the label safely. Update label.text directly inside the closure without DispatchQueue risks UI bugs. Call label.text = text before task.resume() updates UI before data is fetched. Use a background thread to update label.text wrongly uses background thread for UI.
Final Answer:
Use DispatchQueue.main.async { label.text = text } inside the closure -> Option C
Quick Check:
UI updates on main thread = Use DispatchQueue.main.async { label.text = text } inside the closure [OK]
Hint: Always update UI on main thread with DispatchQueue.main.async [OK]
Common Mistakes:
Updating UI on background thread
Updating UI before data arrives
Ignoring thread safety for UI changes
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.