### MZDownloadManager Initialization Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Initializes the MZDownloadManager with a session ID, delegate, and a background completion handler. This setup is crucial for managing background downloads. ```APIDOC ## MZDownloadManager Initialization Creates the background `URLSession` with a unique identifier, restores any interrupted tasks that were running before the app was killed, and wires the completion handler required for background session events. ```swift // AppDelegate.swift import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var backgroundSessionCompletionHandler: (() -> Void)? func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) { // Store the system-provided completion handler; MZDownloadManager will // call it after all background events have been delivered. backgroundSessionCompletionHandler = completionHandler } } // ViewController.swift import MZDownloadManager class DownloadListViewController: UITableViewController { lazy var downloadManager: MZDownloadManager = { let sessionID = "com.myapp.BackgroundDownloadSession" let appDelegate = UIApplication.shared.delegate as! AppDelegate let completion = appDelegate.backgroundSessionCompletionHandler return MZDownloadManager(session: sessionID, delegate: self, completion: completion) }() } ``` ``` -------------------------------- ### Add Download Task with Custom Destination Path Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Start a download and specify a custom directory for the finished file. If the directory does not exist, `downloadRequestDestinationDoestNotExists` will be called. ```swift let customDir = (MZUtility.baseFilePath as NSString).appendingPathComponent("Videos") // Create the directory if needed if !FileManager.default.fileExists(atPath: customDir) { try? FileManager.default.createDirectory( atPath: customDir, withIntermediateDirectories: true, attributes: nil ) } downloadManager.addDownloadTask( "wwdc-session.mp4", fileURL: "https://devstreaming-cdn.apple.com/videos/wwdc/2023/session.mp4", destinationPath: customDir ) ``` -------------------------------- ### addDownloadTask — Custom URLRequest Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Starts a download using a fully configured `URLRequest`, enabling custom HTTP headers such as authorization tokens. ```APIDOC ## addDownloadTask — Custom URLRequest Starts a download using a fully configured `URLRequest`, enabling custom HTTP headers such as authorization tokens. ```swift var request = URLRequest(url: URL(string: "https://api.example.com/secure/report.pdf")!) request.httpMethod = "GET" request.setValue("Bearer eyJhbGciOiJIUzI1NiJ9...", forHTTPHeaderField: "Authorization") request.setValue("application/pdf", forHTTPHeaderField: "Accept") downloadManager.addDownloadTask( "monthly-report.pdf", request: request, destinationPath: MZUtility.baseFilePath ) ``` ``` -------------------------------- ### addDownloadTask — Simple URL String Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Starts a download task using a plain URL string. The file is saved to the default Documents directory. ```APIDOC ## addDownloadTask — Simple URL String Starts a download task using a plain URL string and saves the file to the default Documents directory. ```swift // Queue a single file download to the default Documents path downloadManager.addDownloadTask( "swift-evolution.pdf", fileURL: "https://download.swift.org/swift-evolution/proposals.pdf" ) // The delegate fires immediately: // downloadRequestStarted(_:index:) → index 0 ``` ``` -------------------------------- ### Install MZDownloadManager with CocoaPods Source: https://github.com/mzeeshanid/mzdownloadmanager/blob/master/README.md Add this line to your Podfile to install MZDownloadManager using CocoaPods. ```ruby pod "MZDownloadManager" ``` -------------------------------- ### addDownloadTask — Custom Destination Path Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Starts a download and moves the finished file to a caller-specified directory. If the directory is missing at completion time, `downloadRequestDestinationDoestNotExists` is called. ```APIDOC ## addDownloadTask — Custom Destination Path Starts a download and moves the finished file to a caller-specified directory. If the directory is missing at completion time, `downloadRequestDestinationDoestNotExists` is called instead of the failure delegate. ```swift let customDir = (MZUtility.baseFilePath as NSString).appendingPathComponent("Videos") // Create the directory if needed if !FileManager.default.fileExists(atPath: customDir) { try? FileManager.default.createDirectory( atPath: customDir, withIntermediateDirectories: true, attributes: nil ) } downloadManager.addDownloadTask( "wwdc-session.mp4", fileURL: "https://devstreaming-cdn.apple.com/videos/wwdc/2023/session.mp4", destinationPath: customDir ) ``` ``` -------------------------------- ### Initialize MZDownloadManager with Background Session Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Set up the background URLSession and restore interrupted tasks. Ensure the AppDelegate handles background session events and provides the completion handler. ```swift // AppDelegate.swift import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var backgroundSessionCompletionHandler: (() -> Void)? func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) { // Store the system-provided completion handler; MZDownloadManager will // call it after all background events have been delivered. backgroundSessionCompletionHandler = completionHandler } } // ViewController.swift import MZDownloadManager class DownloadListViewController: UITableViewController { lazy var downloadManager: MZDownloadManager = { let sessionID = "com.myapp.BackgroundDownloadSession" let appDelegate = UIApplication.shared.delegate as! AppDelegate let completion = appDelegate.backgroundSessionCompletionHandler return MZDownloadManager(session: sessionID, delegate: self, completion: completion) }() } ``` -------------------------------- ### Add Download Task with Simple URL Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Queue a download task using a plain URL string. The file will be saved to the default Documents directory. The delegate method `downloadRequestStarted(_:index:)` will be called upon initiation. ```swift // Queue a single file download to the default Documents path downloadManager.addDownloadTask( "swift-evolution.pdf", fileURL: "https://download.swift.org/swift-evolution/proposals.pdf" ) // The delegate fires immediately: // downloadRequestStarted(_:index:) → index 0 ``` -------------------------------- ### Add Download Task with Custom URLRequest Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Initiate a download using a fully configured `URLRequest`, allowing for custom HTTP headers like authorization tokens. ```swift var request = URLRequest(url: URL(string: "https://api.example.com/secure/report.pdf")!) request.httpMethod = "GET" request.setValue("Bearer eyJhbGciOiJIUzI1NiJ9...", forHTTPHeaderField: "Authorization") request.setValue("application/pdf", forHTTPHeaderField: "Accept") downloadManager.addDownloadTask( "monthly-report.pdf", request: request, destinationPath: MZUtility.baseFilePath ) ``` -------------------------------- ### MZUtility Helper Functions Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Utilize static methods for file size formatting, generating unique filenames, excluding files from iCloud backup, and checking free disk space. Also demonstrates observing download completion notifications. ```swift // Human-readable file size let bytes: Int64 = 52_428_800 // 50 MB let size = MZUtility.calculateFileSizeInUnit(bytes) // 50.0 let unit = MZUtility.calculateUnit(bytes) // "MB" print("\(size) \(unit)") // "50.0 MB" ``` ```swift // Unique filename to avoid overwrites let docPath = MZUtility.baseFilePath // ~/ let candidate = (docPath as NSString).appendingPathComponent("report.pdf") let unique = MZUtility.getUniqueFileNameWithPath(candidate as NSString) // Returns "report.pdf" if free, "report(1).pdf" if taken, etc. ``` ```swift // Exclude a downloaded file from iCloud backup let filePath = (MZUtility.baseFilePath as NSString).appendingPathComponent("video.mp4") let excluded = MZUtility.addSkipBackupAttributeToItemAtURL(filePath as NSString) print(excluded ? "Excluded from backup" : "File not found") ``` ```swift // Check available disk space before starting a large download if let freeSpace = MZUtility.getFreeDiskspace() { let freeGB = freeSpace.int64Value / (1024 * 1024 * 1024) if freeGB < 1 { print("Warning: less than 1 GB free") } } ``` ```swift // DownloadCompletedNotif — observe globally NotificationCenter.default.addObserver( forName: NSNotification.Name(MZUtility.DownloadCompletedNotif), object: nil, queue: .main ) { notification in if let filePath = notification.object as? String { print("File saved at: \(filePath)") } } ``` -------------------------------- ### Implement MZDownloadManagerDelegate for Download Updates Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Implement required delegate methods to update the UI with download progress, speed, remaining time, and file sizes. This method is called on the main queue. ```swift extension DownloadListViewController: MZDownloadManagerDelegate { // REQUIRED — called on main queue each time bytes are received func downloadRequestDidUpdateProgress(_ downloadModel: MZDownloadModel, index: Int) { let indexPath = IndexPath(row: index, section: 0) if let cell = tableView.cellForRow(at: indexPath) as? DownloadCell { cell.progressView.progress = downloadModel.progress if let speed = downloadModel.speed { cell.speedLabel.text = String(format: "%.1f %@/s", speed.speed, speed.unit) } if let remaining = downloadModel.remainingTime { cell.etaLabel.text = String(format: "%02d:%02d:%02d", remaining.hours, remaining.minutes, remaining.seconds) } if let file = downloadModel.file, let downloaded = downloadModel.downloadedFile { cell.sizeLabel.text = String(format: "%.1f %@ / %.1f %@", downloaded.size, downloaded.unit, file.size, file.unit) } } } // REQUIRED — repopulates tasks interrupted by force-quit or background disable func downloadRequestDidPopulatedInterruptedTasks(_ downloadModels: [MZDownloadModel]) { tableView.reloadData() } // OPTIONAL callbacks func downloadRequestStarted(_ downloadModel: MZDownloadModel, index: Int) { tableView.insertRows(at: [IndexPath(row: index, section: 0)], with: .fade) } func downloadRequestDidPaused(_ downloadModel: MZDownloadModel, index: Int) { tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none) } func downloadRequestDidResumed(_ downloadModel: MZDownloadModel, index: Int) { tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none) } func downloadRequestCanceled(_ downloadModel: MZDownloadModel, index: Int) { tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .left) } func downloadRequestFinished(_ downloadModel: MZDownloadModel, index: Int) { tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .left) // Notify other parts of the app let filePath = (MZUtility.baseFilePath as NSString) .appendingPathComponent(downloadModel.fileName) NotificationCenter.default.post( name: NSNotification.Name(MZUtility.DownloadCompletedNotif), object: filePath ) // Show local notification when app is in background downloadManager.presentNotificationForDownload( "Open", notifBody: "\(downloadModel.fileName!) finished downloading" ) } func downloadRequestDidFailedWithError(_ error: NSError, downloadModel: MZDownloadModel, index: Int) { print("Download failed: \(downloadModel.fileName!) — \(error.localizedDescription)") tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none) } // Called on the SESSION QUEUE (not main queue) when the destination folder is missing func downloadRequestDestinationDoestNotExists(_ downloadModel: MZDownloadModel, index: Int, location: URL) { let fallback = MZUtility.baseFilePath + "/Recovered" try? FileManager.default.createDirectory(atPath: fallback, withIntermediateDirectories: true, attributes: nil) let uniqueName = MZUtility.getUniqueFileNameWithPath( (fallback as NSString).appendingPathComponent(downloadModel.fileName) as NSString ) let dest = URL(fileURLWithPath: fallback + "/" + (uniqueName as String)) try? FileManager.default.moveItem(at: location, to: dest) } } ``` -------------------------------- ### MZUtility Helper Functions Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Provides static utility methods for file size formatting, generating unique filenames, excluding files from iCloud backup, and querying free disk space. ```APIDOC ## MZUtility — Helper Functions Static utility methods for file size formatting, unique filename generation, iCloud backup exclusion, and free disk space queries. ```swift // Human-readable file size let bytes: Int64 = 52_428_800 // 50 MB let size = MZUtility.calculateFileSizeInUnit(bytes) // 50.0 let unit = MZUtility.calculateUnit(bytes) // "MB" print("\(size) \(unit)") // "50.0 MB" // Unique filename to avoid overwrites let docPath = MZUtility.baseFilePath // ~/Documents let candidate = (docPath as NSString).appendingPathComponent("report.pdf") let unique = MZUtility.getUniqueFileNameWithPath(candidate as NSString) // Returns "report.pdf" if free, "report(1).pdf" if taken, etc. // Exclude a downloaded file from iCloud backup let filePath = (MZUtility.baseFilePath as NSString).appendingPathComponent("video.mp4") let excluded = MZUtility.addSkipBackupAttributeToItemAtURL(filePath as NSString) print(excluded ? "Excluded from backup" : "File not found") // Check available disk space before starting a large download if let freeSpace = MZUtility.getFreeDiskspace() { let freeGB = freeSpace.int64Value / (1024 * 1024 * 1024) if freeGB < 1 { print("Warning: less than 1 GB free") } } // DownloadCompletedNotif — observe globally NotificationCenter.default.addObserver( forName: NSNotification.Name(MZUtility.DownloadCompletedNotif), object: nil, queue: .main ) { notification in if let filePath = notification.object as? String { print("File saved at: \(filePath)") } } ``` ``` -------------------------------- ### Add Download Task with Custom Path Source: https://github.com/mzeeshanid/mzdownloadmanager/blob/master/README.md Use this instance method to add a download task, specifying a custom destination path for the downloaded file. The delegate methods will be called upon completion or if the destination folder does not exist. ```swift public func addDownloadTask(fileName: String, fileURL: String, destinationPath: String) ``` -------------------------------- ### Handle Download Destination Does Not Exist Source: https://github.com/mzeeshanid/mzdownloadmanager/blob/master/README.md Implement this delegate method to handle cases where the specified destination folder for a download does not exist. This method is called on the session's queue. ```swift optional func downloadRequestDestinationDoestNotExists(downloadModel: MZDownloadModel, index: Int, location: NSURL) ``` -------------------------------- ### Configure Default Background Session Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Obtain a pre-configured `URLSessionConfiguration.background` instance using `defaultSessionConfiguration`. Customize properties like cellular access, timeouts, and discretionary scheduling before passing it to the `MZDownloadManager` initializer. ```swift // Default background configuration let config = MZDownloadManager.defaultSessionConfiguration( identifier: "com.myapp.BackgroundSession" ) // Customize before passing to the manager config.allowsCellularAccess = false // Wi-Fi only config.isDiscretionary = false // Start immediately config.timeoutIntervalForRequest = 60 // 60 s per request config.timeoutIntervalForResource = 3600 // 1 h total resource timeout let downloadManager = MZDownloadManager( session: "com.myapp.BackgroundSession", delegate: self, sessionConfiguration: config, completion: appDelegate.backgroundSessionCompletionHandler ) ``` -------------------------------- ### Inspect MZDownloadModel Properties Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Access runtime state of a download task using MZDownloadModel properties. Useful within delegate callbacks to update UI or check download status. ```swift func inspect(model: MZDownloadModel) { print(model.fileName) // "swift-evolution.pdf" print(model.fileURL) // "https://..." print(model.destinationPath) // "/Documents/PDFs" or "" for default print(model.status) // "Downloading" | "Paused" | "Failed" | "GettingInfo" print(model.progress) // 0.0 ... 1.0 (fraction complete) if let file = model.file { print("\(file.size) \(file.unit)") // e.g. "12.4 MB" } if let dl = model.downloadedFile { print("\(dl.size) \(dl.unit)") // e.g. "3.1 MB" } if let spd = model.speed { print("\(spd.speed) \(spd.unit)/s") // e.g. "512.0 KB/s" } if let t = model.remainingTime { print(String(format: "%02d:%02d:%02d", t.hours, t.minutes, t.seconds)) } // Direct access to the underlying task if needed print(model.task?.taskIdentifier ?? -1) print(model.startTime ?? Date()) } ``` -------------------------------- ### defaultSessionConfiguration Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Returns a `URLSessionConfiguration.background` instance pre-configured with a supplied identifier. This allows for customization of cellular access, timeouts, and scheduling for background downloads. ```APIDOC ## defaultSessionConfiguration Returns a `URLSessionConfiguration.background` instance pre-configured with the supplied identifier. Pass a custom configuration to the initializer to override cellular access, timeouts, or discretionary scheduling. ```swift // Default background configuration let config = MZDownloadManager.defaultSessionConfiguration( identifier: "com.myapp.BackgroundSession" ) // Customize before passing to the manager config.allowsCellularAccess = false // Wi-Fi only config.isDiscretionary = false // Start immediately config.timeoutIntervalForRequest = 60 // 60 s per request config.timeoutIntervalForResource = 3600 // 1 h total resource timeout let downloadManager = MZDownloadManager( session: "com.myapp.BackgroundSession", delegate: self, sessionConfiguration: config, completion: appDelegate.backgroundSessionCompletionHandler ) ``` ``` -------------------------------- ### Resume Download Task Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Resumes a download task that was previously paused. If the task is already in progress, this action is ignored. Triggers the `downloadRequestDidResumed` delegate method. ```swift func resumeTapped(at index: Int) { let model = downloadManager.downloadingArray[index] guard model.status == TaskStatus.paused.description() else { return } downloadManager.resumeDownloadTaskAtIndex(index) // Delegate: downloadRequestDidResumed(model, index: index) } ``` -------------------------------- ### retryDownloadTaskAtIndex Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Resumes a failed download task. Uses resume data when available to continue from where the download stopped; otherwise restarts from the beginning. ```APIDOC ## retryDownloadTaskAtIndex ### Description Resumes a failed download task. Uses resume data when available to continue from where the download stopped; otherwise restarts from the beginning. ### Method `downloadManager.retryDownloadTaskAtIndex(index: Int)` ### Parameters #### Path Parameters - **index** (Int) - Required - The index of the download task to retry. ``` -------------------------------- ### Retry Failed Download Task Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Resumes a download task that has failed. It attempts to resume from the last point if resume data is available, otherwise, it restarts the download from the beginning. The status is reset to 'Downloading'. ```swift func retryFailedDownload(at index: Int) { let model = downloadManager.downloadingArray[index] guard model.status == TaskStatus.failed.description() else { return } downloadManager.retryDownloadTaskAtIndex(index) // task.resume() is called; status set back to "Downloading" } ``` -------------------------------- ### Present Local Notification for Download Completion Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Call `presentNotificationForDownload` within download completion or failure delegate methods to alert the user when the app is in the background. This function delivers a `UILocalNotification`. ```swift func downloadRequestFinished(_ downloadModel: MZDownloadModel, index: Int) { downloadManager.presentNotificationForDownload( "View File", notifBody: "\(downloadModel.fileName!) has finished downloading." ) // Shows a local notification with: // alertAction: "View File" // alertBody: "report.pdf has finished downloading." // sound: default // badge: incremented by 1 } ``` -------------------------------- ### resumeDownloadTaskAtIndex Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Resumes a previously paused download task. If the task is already downloading, the call is silently ignored. Fires downloadRequestDidResumed(_:index:). ```APIDOC ## resumeDownloadTaskAtIndex ### Description Resumes a previously paused download task. If the task is already downloading the call is silently ignored. Fires `downloadRequestDidResumed(_:index:)`. ### Method `downloadManager.resumeDownloadTaskAtIndex(index: Int)` ### Parameters #### Path Parameters - **index** (Int) - Required - The index of the download task to resume. ``` -------------------------------- ### presentNotificationForDownload Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Delivers a `UILocalNotification` when the app is in the background state. This function should be called within `downloadRequestFinished` or `downloadRequestDidFailedWithError` to alert the user about download completion or failure. ```APIDOC ## presentNotificationForDownload Delivers a `UILocalNotification` when the app is in the background state. Call this inside `downloadRequestFinished` or `downloadRequestDidFailedWithError` to alert the user. ```swift func downloadRequestFinished(_ downloadModel: MZDownloadModel, index: Int) { downloadManager.presentNotificationForDownload( "View File", notifBody: "\(downloadModel.fileName!) has finished downloading." ) // Shows a local notification with: // alertAction: "View File" // alertBody: "report.pdf has finished downloading." // sound: default // badge: incremented by 1 } ``` ``` -------------------------------- ### Pause Download Task Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Suspends an active download task. If the task is already paused, this action is ignored. Triggers the `downloadRequestDidPaused` delegate method. ```swift extension DownloadListViewController: UITableViewDelegate { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let model = downloadManager.downloadingArray[indexPath.row] if model.status == TaskStatus.downloading.description() { downloadManager.pauseDownloadTaskAtIndex(indexPath.row) // Delegate: downloadRequestDidPaused(model, index: indexPath.row) } } } ``` -------------------------------- ### cancelTaskAtIndex Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Cancels a download task entirely and removes it from downloadingArray. Fires downloadRequestCanceled(_:index:). ```APIDOC ## cancelTaskAtIndex ### Description Cancels a download task entirely and removes it from `downloadingArray`. Fires `downloadRequestCanceled(_:index:)`. ### Method `downloadManager.cancelTaskAtIndex(index: Int)` ### Parameters #### Path Parameters - **index** (Int) - Required - The index of the download task to cancel. ``` -------------------------------- ### Cancel Download Task Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Cancels a download task entirely and removes it from the list of active downloads. Triggers the `downloadRequestCanceled` delegate method. ```swift override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { downloadManager.cancelTaskAtIndex(indexPath.row) // Delegate: downloadRequestCanceled(model, index: indexPath.row) // Remove the row in the delegate callback, not here } } ``` -------------------------------- ### pauseDownloadTaskAtIndex Source: https://context7.com/mzeeshanid/mzdownloadmanager/llms.txt Suspends the underlying URLSessionDownloadTask for a running download. If the task is already paused, the call is silently ignored. Fires downloadRequestDidPaused(_:index:). ```APIDOC ## pauseDownloadTaskAtIndex ### Description Suspends the underlying `URLSessionDownloadTask` for a running download. If the task is already paused the call is silently ignored. Fires `downloadRequestDidPaused(_:index:)`. ### Method `downloadManager.pauseDownloadTaskAtIndex(index: Int)` ### Parameters #### Path Parameters - **index** (Int) - Required - The index of the download task to pause. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.