Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

URLSession Tutorial

Introduction

Networking is a vital aspect of modern iOS applications. Whether you are fetching data from a web service, downloading files, or uploading content, understanding how to handle network requests is crucial. In iOS development, URLSession is the key class for managing HTTP and HTTPS requests. This tutorial will guide you through everything you need to know about URLSession, from basic GET requests to handling authentication and downloading files.

Setting Up URLSession

To start using URLSession, you first need to create an instance of it. You can use the default session configuration for most cases. Here is a simple example of setting up a URLSession:

let session = URLSession.shared

This creates a shared singleton session instance with the default configuration.

Making a GET Request

Making a GET request is one of the most common operations. Here's how you can do it using URLSession:

if let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") {
    let task = URLSession.shared.dataTask(with: url) { data, response, error in
        if let error = error {
            print("Error: \(error)")
            return
        }
        
        if let data = data {
            if let json = try? JSONSerialization.jsonObject(with: data, options: []) {
                print("Response JSON: \(json)")
            }
        }
    }
    task.resume()
}

This code creates a data task that fetches a JSON object from a given URL. The resume() method starts the task.

Handling POST Requests

Sending data to a server usually involves a POST request. Here is how you can handle a POST request with URLSession:

if let url = URL(string: "https://jsonplaceholder.typicode.com/posts") {
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    let postString = "title=foo&body=bar&userId=1"
    request.httpBody = postString.data(using: .utf8)
    
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if let error = error {
            print("Error: \(error)")
            return
        }

        if let data = data {
            if let json = try? JSONSerialization.jsonObject(with: data, options: []) {
                print("Response JSON: \(json)")
            }
        }
    }
    task.resume()
}

In this example, we configure a URLRequest for a POST request and set the HTTP body with the data to be sent.

Handling Authentication

Sometimes, you may need to handle HTTP authentication with your requests. Here's an example of how to add basic authentication headers:

if let url = URL(string: "https://jsonplaceholder.typicode.com/posts") {
    var request = URLRequest(url: url)
    request.httpMethod = "GET"
    
    let username = "user"
    let password = "password"
    let loginString = "\(username):\(password)"
    guard let loginData = loginString.data(using: .utf8) else { return }
    let base64LoginString = loginData.base64EncodedString()
    
    request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
    
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if let error = error {
            print("Error: \(error)")
            return
        }

        if let data = data {
            if let json = try? JSONSerialization.jsonObject(with: data, options: []) {
                print("Response JSON: \(json)")
            }
        }
    }
    task.resume()
}

In this example, we add an Authorization header with a Base64-encoded string of the username and password.

Downloading Files

Downloading large files can be managed efficiently using URLSessionDownloadTask. Here's an example:

if let url = URL(string: "https://example.com/largefile.zip") {
    let task = URLSession.shared.downloadTask(with: url) { localURL, response, error in
        if let error = error {
            print("Error: \(error)")
            return
        }

        if let localURL = localURL {
            do {
                let documentsURL = try FileManager.default.url(
                    for: .documentDirectory,
                    in: .userDomainMask,
                    appropriateFor: nil,
                    create: false
                )
                let savedURL = documentsURL.appendingPathComponent(localURL.lastPathComponent)
                try FileManager.default.moveItem(at: localURL, to: savedURL)
                print("File saved to \(savedURL)")
            } catch {
                print("File error: \(error)")
            }
        }
    }
    task.resume()
}

This code downloads a file from the given URL and saves it to the app's documents directory.

Conclusion

In this tutorial, we covered the basics of using URLSession in iOS development. We went through making GET and POST requests, handling authentication, and downloading files. URLSession is a powerful and flexible API that can handle a variety of networking tasks. With this knowledge, you should be well-equipped to implement networking in your iOS applications.