0
0
iOS Swiftmobile~5 mins

URLSession basics in iOS Swift

Choose your learning style9 modes available
Introduction

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 in
    if 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 in
    if 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 in
            if 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.