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.
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)%")
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?