How do I upload and download files with progress in Swift?

In Swift, you can upload and download files using URLSession. Both operations can track progress by utilizing the delegate methods of URLSession. Below is an example demonstrating how to upload and download files with progress tracking.

Keywords: Swift, URLSession, file upload, file download, progress tracking, networking
Description: This example demonstrates how to handle file uploads and downloads in Swift using URLSession, along with tracking the progress of these operations.

import UIKit

class FileTransferViewController: UIViewController, URLSessionDelegate, URLSessionTaskDelegate {
    
    func uploadFile(url: URL, fileData: Data) {
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        
        let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
        let uploadTask = session.uploadTask(with: request, from: fileData)
        
        uploadTask.resume()
    }
    
    func downloadFile(url: URL) {
        let request = URLRequest(url: url)
        let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
        let downloadTask = session.downloadTask(with: request)
        
        downloadTask.resume()
    }
    
    // MARK: - URLSession Task Delegate Methods

    func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
        let progress = Double(totalBytesSent) / Double(totalBytesExpectedToSend)
        print("Upload Progress: \(progress * 100)%")
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        if let error = error {
            print("Error: \(error.localizedDescription)")
        } else {
            print("Upload completed successfully.")
        }
    }
    
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        // Handle the downloaded file
        print("Download completed to: \(location)")
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didUpdateProgress totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) {
        let progress = Double(totalBytesReceived) / Double(totalBytesExpectedToReceive)
        print("Download Progress: \(progress * 100)%")
    }
}
    

Keywords: Swift URLSession file upload file download progress tracking networking