SDEDownloadManager

@objcMembers open class SDEDownloadManager: NSObject

SDEDownloadManager is a download management tool, support background download.

If you want to build interface to display and manage download tasks, or track download activity, DownloadListController is a good choice, which is a UITableViewController subclass to coordinate with SDEDownloadManager and has rich options to reduce a lot of work for you.

Features:

  • Basic download management: download/pause/stop/resume/restart/delete

All actions for the download task in SDEDownloadManager are basis on its download URL string. SDEDownloadManager doesn’t support reduplicative task, but it doesn’t disable it totally: URL(string: URLString) and URL(string: URLString.uppercased()) request the same file.

  • As a data source for UITableView/UICollectionView

SDEDownloadManager maintains a download list([[String]]), so it could manage download task based on its location(IndexPath) also.

  • Sort download list

Use sortListBy(type:order:) to change the order of download list. It supports to switch between five types: manual, addTime, fileName, fileSize and fileType. I classify these sort types as two modes: manual mode and predefined mode(latter four types).You could choose its sort mode when create a download manager in manager(identifier:manualMode:).

Specially, in manual mode, a section in downloadList must has a title, and it will lose all section titles when switching from manual mode to predefined mode. And all tasks will be integrated into a single section with a placeholder title when switching from predefined mode to manual mode.

In manual mode, reorder tasks by moveTask(at:to:) and moveTasks(inSection:to).

sortListBy(type:order:) is limited by file meta info and just use four predefined sort types, sortListBy(order:taskTrait:traitAscending:taskAscending:) free you to custom sort function.

  • Control download count

Adjust maxDownloadCount to control the maximum count of tasks which download at the same time. Don’t worry, it’s good as you think.

  • Track download activity: download progress and speed

Download activity info is provided in downloadActivityHandler, you could use the closure to update view. Call beginTrackingDownloadActivity() to track download activity, it executes downloadActivityHandler every second in the background until there is no more download or call stopTrackingDownloadActivity() to stop it.

  • Data persistence

When you need, call saveData(). SDEDownloadManager use property list serialization to save data, so when you add custom meta info for task by fetchMetaInfoHandler, it must be property list object. It has enough load and save performance for usual scenes which has almost under 10000 records. You’d better test it in your scene. If load performance is not good in your scene, I suggest that you create download manager in advance to leave time to load data.

  • Cache thumbnails for files

Request thumbnail by requestThumbnail(forTask:targetHeight:orLaterProvidedInHandler:). Generally, only image and video should have thumbnail, but there are some scenes where you want to associate a image with the file, e.g., an album art for the song, a poster for the movie. You can custom thumbnail for any file(except for image) by setCustomThumbnail(_:forTask:cacheInMemoryOnly:).

  • Authentication

SDEDownloadManager handle part authentication types for you: Basic, Digest, and server trust. For other authentication types, you could handle them by sessionDidReceiveChallengeHandler and taskDidReceiveChallengeHandler.

  • Custom Other Behaviors in Session Delegate

SDEDownloadManager use NSURLSessionDownloadTask to download files, and session delegate is internal, I leave closure interfaces to custom behaviors in session delegate. See MARK: Closures to Custom Behaviors in Session Delegate.

  • Trash

Enable this feature by isTrashOpened. If true, task to delete will be moved to the trash first; if false, task is deleted directly.

  • Handle app force quit in downloading and you don’t have to do anything.
  • Create a download manager with specified identifier.

    After download manager is inited, it begins to load data in the background immediately.

    Choose sort mode based on your usage scenario. SDEDownloadManager has two sort mode: manual and predefined mode. The two sort modes can switch to each other. Except for obvious sort difference, what’s difference between with two modes?

    1. Download new file. In predefined mode, you just need to offer download URL, but in manual mode, you must offer its insert location in downloadList, which is [[String]] and is designed for UITableView/UICollectionView.
    2. A section in UITableView with .plain style can’t be distinguished from last section if it doesn’t have a title, so in manual mode, you must offer a title.

    Although you can switch between with two sort modes freely, switching from manual mode to predefined mode will lose all section titles, and switching from predefined mode to manual mode will integrate all tasks into one section with a placeholder title, so choose sort mode based on your usage scenario discreetly.

    Declaration

    Swift

    public static func manager(identifier: String, manualMode: Bool = false) -> SDEDownloadManager

    Parameters

    identifier

    The unique identifier. If a download manager object with the same identifier exists in the memory, return it.

    manualMode

    Choose manual sort mode as initial sort mode or not. The default value is false. This property is valid only when you are the first time to create a SDEDownloadManager object with the identifier, if app has record about identifier, this property is ignored. If true, download manager is inited in manual sort mode, which means it’s your responsibility to order task locations; if false, it’s inited with default sort type: addTime. Sort mode could be changd by sortListBy(type:order:).

    Return Value

    A SDEDownloadManager object. If a download manager object with the same identifier exists in the memory, return it. This method is thread safe, other method is not thread safe if it’s not indicated thread safe explicitly.

  • This method is synchronous, and it’s executed in current thread. Everytime app enter background, SDEDownloadManager calls this method automatically.

    Data are splited into several parts and are saved separately, only changed part will be saved, so it has a good performance at the most time if data is not huge(like under 10000 records). You’d better test its performance in your environment.

    Declaration

    Swift

    public func saveData()
  • Check whether specified download manager could be destoryed safely. This method returns true only when:

    1. The specified download manager is existed in the database.
    2. The specified download manager is not existed in the memory. Because of implementation of manager(identifier:manualMode:), once it’s called, returned manager is existed in the memory until app is exited.

    Declaration

    Swift

    public static func isDestoryableForManager(_ identifier: String) -> Bool

    Parameters

    identifier

    The download manager’s identifier.

    Return Value

    Returns a Boolean value indicating whether the download manager could be destoryed safely.

  • Destroy underlying data of specified download manager, not includes live data if specified download manager exists in the memory already. You should call isDestoryableForManager(_:) to check whether specified download manager is destoryable before calling this method because destoryed data cannot be recovered.

    Note: This method won’t delete downloaded files.

    Declaration

    Swift

    public static func destoryManager(_ identifier: String) -> Bool

    Parameters

    identifier

    The download manager’s identifier.

    Return Value

    Return true if underlying data are destoryed.

  • The unique identifier. Specify it in manager(identifier:manualMode:), if a SDEDownloadManager object with the identifier exists in the memory already, this methos return it directly.

    Declaration

    Swift

    public let identifier: String
  • A Boolean value indicating whether data is loaded. After a SDEDownloadManager object is inited, it loads data in the background. Usually it’s very soon to load data.

    Declaration

    Swift

    public var isDataLoaded: Bool
  • The current sort type of download list(read-only). The default value is .addTime.

    sortType has five values: .manual, .addTime, .fileName, .fileSize, .fileType. They are classified as two modes: manual mode(.manual) and predefined mode(latter four types). For .manual type, you determine task locations; for latter four types, task locations are determined by sortType and sortOrder together.

    Call sortListBy(type:order:) to switch between sort types.

    Declaration

    Swift

    public var sortType: ComparisonType
  • .ascending or .descending. This property is ignored if sortType == .manual. The default value is .ascending.

    You can call sortListBy(sortType:sortOrder:) to change sort order.

    Declaration

    Swift

    public var sortOrder: ComparisonOrder
  • A URL string array includes all section titles for UITableView/UICollectionView.

    Declaration

    Swift

    public var sectionTitles: [String]?
  • URL strings of current all tasks.

    Declaration

    Swift

    public var downloadList: [[String]]?
  • A URL string array includes tasks to delete. Sorted by delete time and the head is the most recent deleted task.

    Declaration

    Swift

    public var toDeleteList: [String]?
  • A URL string array includes all unfinished tasks(not include task in toDeleteList). It’s dynamic: URL string will be removed from this list after its task is finished. Sorted by add time in downloadList and the head is the most recent added task.

    Declaration

    Swift

    public var unfinishedList: [String]?
  • A URL string set includes all tasks in downloadList.

    Declaration

    Swift

    public var downloadTaskSet: Set<String>?
  • A URL string set includes all tasks in the download manager: downloadList and toDeleteList.

    Declaration

    Swift

    public var allTasksSet: Set<String>?
  • Section count of downloadList.

    Declaration

    Swift

    public var sectionCount: Int
  • Task count in the specified section.

    Declaration

    Swift

    public func taskCountInSection(_ section:Int) -> Int

    Parameters

    section

    Section index of downloadList.

    Return Value

    Task count. Return -1 if section index is beyond bounds.

  • Header title used in UITableView/UICollectionView.

    Declaration

    Swift

    public func titleForHeaderInSection(_ section: Int) -> String?

    Parameters

    section

    Section index of downloadList.

    Return Value

    Header title string or nil.

  • Download a group of new files in predefined sort mode(sortType != .manual) and return locations of new files in downloadList immediately. If data is not loaded, this method will wait.

    If current sortType is not .addTime, download mananger switch to .addTime automatically.

    If downloadNewFileImmediately is false, this method just add a record, you can start the task by resumeTasks(_:successOrFailHandler:).

    Precondition

    sortType != .manual, otherwise, return nil directly.

    Declaration

    Swift

    public func download(_ URLStrings: [String], successOrFailHandler: ((_ URLString: String, _ fileLocation: URL?, _ error: NSError?) -> Void)? = nil) -> [IndexPath]?

    Parameters

    URLStrings

    The string array of download URL. Repeated or invalid URL will be filtered. It’s your responsibility to encode URL string if it contains Non-ASCII charater. Use addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) or computed property percentEncodingURLQueryString in the extension to encode string.

    successOrFailHandler

    A temporary closure to execute after a task is successful, or failed (not include cancelling task) to replace taskSuccessOrFailHandler which is executed for every task. The default value is nil. Closure parameters fileLocation and error, only one is not nil at the same time. Check parameters in taskSuccessOrFailHandler property, they are same.

    Return Value

    Locations of new tasks in downloadList. If no task is added, return nil.

  • Insert an empty section as placeholder in manual sort mode(sortType == .manual) and return a Boolean value indicating whether insertion is successful. If data is not loaded, this method will wait.

    Precondition

    sortType == .manual.

    Declaration

    Swift

    public func insertPlaceHolderSectionInManualModeAtSection(_ section: Int, withTitle title: String) -> Bool

    Parameters

    section

    Section location in downloadList. If it’s beyond the bounds, return false.

    title

    Title for section header view.

    Return Value

    A Boolean value indicating whether insertion is successful.

  • Download a group of new files in manual sort mode(sortType == .manual), insert them in downloadList at the section which you specify, and return a Boolean value indicating whether insertion is successful immediately. downloadList is a two-dimensional string array: [[String]]. If data is not loaded, this method will wait.

    Precondition

    sortType == .manual.

    Declaration

    Swift

    public func download(_ URLStrings: [String], inManualModeAtSection section: Int, withTitle title: String) -> Bool

    Parameters

    URLStrings

    The string array of download URL. Repeated or invalid URL will be filtered. It’s your responsibility to encode URL string if it contains Non-ASCII charater. Use addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) or computed property percentEncodingURLQueryString in the extension to encode string.

    section

    Section location in downloadList. If it’s beyond the bounds, return false.

    title

    Titles for section header view. Tip: There is no header view in UITableView if its section title is empty string “”, and if tableView’s style is .plain, section is distinguished from last section.

    Return Value

    A Boolean value indicating whether insertion is successful.

  • Download several groups of new files in manual sort mode(sortType == .manual), insert them in downloadList at the section which you specify, and return indexes of inserted sections in downloadList immediately. downloadList is a two-dimensional string array: [[String]]. If data is not loaded, this method will wait.

    Precondition

    sortType == .manual.

    Declaration

    Swift

    public func download(_ URLStringsList: [[String]], inManualModeAtSection section: Int, withTitles titles: [String]) -> IndexSet?

    Parameters

    URLStringsList

    The download URLs of a two-dimensional array. Any Non-ASII, repeated URL will be filterd.

    section

    Section location in downloadList. If it’s beyond the bounds, return nil.

    titles

    Titles for section header view. Its count should be equal to count of parameter URLStringsList, more is OK, otherwise return nil. Tip: There is no header view in UITableView if its section title is empty string “”, and if tableView’s style is .plain, section is distinguished from last section.

    Return Value

    Indexes of inserted sections in downloadList. If no task is added, return nil.

  • Download a group of new files in manual mode(sortType == .manual), insert them in downloadList at the location which you specify, and return inserted locations in downloadList immediately. If data is not loaded, this method will wait.

    Precondition

    sortType == .manual

    Declaration

    Swift

    public func download(_ URLStrings: [String], inManualModeAt indexPath: IndexPath) -> [IndexPath]?

    Parameters

    URLStrings

    The download URL strings. Any Non-ASII, repeated URL will be filterd.

    indexPath

    Insert location in downloadList. The section in the parameter must be existed.

    Return Value

    Insert locations in downloadList. If no task is added, return nil.

  • Take over outer download task. If data is not loaded, this method will wait.

    Declaration

    Swift

    public func resumeOuterDownload(with resumeData: Data, insertAt indexPath: IndexPath?) -> Bool

    Parameters

    resumeData

    The data to resume download.

    indexPath

    Insert location in downloadList. If sortType == .manual, this value must be not nil; if sortType != .manual, this value is ignored.

    Return Value

    A Boolean value indicating whether this download is taked over.

  • Resume(continue) tasks and return tasks which are resumed successfully.

    This method is not used to download new files, if you want that, use download(_:) series.

    A task can be resumed if it satisfies the following conditions:

    1. download manager has not reach maxDownloadCount;
    2. URL is in downloadList; If task is in toDeleteList and you want to resume it, you must first restore it back to downloadList by restoreToDeletedTasks(_:toLocation:).
    3. task can be resumed: its state is not finished and downloading.

    Declaration

    Swift

    public func resumeTasks(_ URLStrings: [String], successOrFailHandler: ((_ URLString: String, _ fileLocation: URL?, _ error: NSError?) -> Void)? = nil) -> [String]?

    Parameters

    URLStrings

    An array of URL string of task which you want to resume.

    successOrFailHandler

    A temporary closure to execute after a task is successful, or failed (not include cancelling task) to replace taskSuccessOrFailHandler which is executed for every task. The default value is nil. Closure parameters fileLocation and error, only one is not nil at the same time. Check parameters in taskSuccessOrFailHandler property, they are same.

    Return Value

    An array of URL string of task which is resumed successfully. If no task is resumed, return nil.

  • Pause downloading tasks and return tasks which are paused successfully. The method has no effect if task is not downloading.

    Declaration

    Swift

    public func pauseTasks(_ URLStrings: [String]) -> [String]?

    Parameters

    URLStrings

    An array of URL string of task which you want to pause.

    Return Value

    An array of URL string of task which is paused successfully, or nil if no task is paused.

  • Stop downloading/paused tasks and cancel waitting tasks and return tasks which are stopped successfully.

    How to define stop? SDEDownloadManager use NSURLSessionDownloadTask to download files. Usually we pause a task by suspend(), and the task still keeps connection with server; here stop a task by cancel(byProducingResumeData:), disconnect from server.

    Declaration

    Swift

    public func stopTasks(_ URLStrings: [String]) -> [String]?

    Parameters

    URLStrings

    An array of URL string of task which you want to stop.

    Return Value

    An array of URL string of task which is stopped successfully, or nil if no task is stopped.

  • Delete task records and choose to delete relative files or not, and return a Ditionary includes deleted task’s URL string and its original location in downloadList. If data is not loaded, this method will wait.

    PS.: If you want to delete many tasks, you better use deleteTasks(at:keepFinishedFile:deletionHandler:), this method takes more time when delete same tasks.

    If isTrashOpened == true, tasks will be moved to toDeleteList.

    If you want to do something after a task is deleted in this method, use deleteCompletionHandler. After this method returns, deleteCompletionHandler is reset to nil.

    Declaration

    Swift

    public func deleteTasks(_ URLStrings: [String], keepFinishedFile: Bool = false) -> Dictionary<String, IndexPath>?

    Parameters

    URLStrings

    An array of URL string of task which you want to delete.

    keepFinishedFile

    Just works for finished task whose file is downloaded completely. For task whose state is not finished, this parameter is ignored. The default value is false. You can get file location by fileURL(forTask:) before calling this method.

    Return Value

    A Dictionary includes deleted task info. Key: URL string of deleted task, Value: task original location in downloadList. If no task is deleted, return nil.

  • Delete relative files of tasks but keep record, and return locations of tasks whose files are deleted successfully. If data is not loaded, this method will wait.

    Specially, if task’s state is .pending, it’s also included in returned result.

    If you want to do something after a task is deleted in this method, use deleteCompletionHandler. After this method returns, deleteCompletionHandler is reset to nil.

    Declaration

    Swift

    public func deleteFilesOfTasks(_ URLStrings: [String]) -> [String]?

    Parameters

    URLStrings

    An array of URL string of task whose file you want to delete.

    Return Value

    An array of URL string of task whose file is deleted successfully, or nil if no file is deleted.

  • Redownload file if task’s finished or stopped and return locations of tasks which are restarted successfully. The downloaded file will be deleted before restart.

    Declaration

    Swift

    public func restartTasks(_ URLStrings: [String]) -> [String]?

    Parameters

    URLStrings

    An array of URL string of task which you want to restart.

    Return Value

    An array of URL string of task which is restarted successfully, or nil if no task is restarted.

  • Resume all unfinished tasks. What’s difference between this method and resumeTasks(_:)? If download manager has reach maxDownloadCount, this method will put task into waitting list, the latter won’t.

    Declaration

    Swift

    public func resumeAllTasks(underLimit limited: Bool = true)

    Parameters

    limited

    A switch to lock/unlock the limitation of maxDownloadCount. If the value is true, keep count of executing task at the same time is not large than maxDownloadCount, the default value is true; if false, unlock maxDownloadCount, maxDownloadCount is setted to OperationQueue.defaultMaxConcurrentOperationCount, which means no limitation.

  • Pause all downloading tasks and dequeue waitting tasks in the queue. If pauseDownloadBySuspendingSessionTask == false, this method call stopAllTasks().

    Declaration

    Swift

    public func pauseAllTasks()
  • Stop all downloading tasks and cancel waitting tasks in the queue.

    Declaration

    Swift

    public func stopAllTasks()
  • Delete all task records and choose to delete relative files or not. If data is not loaded, this method will wait.

    If you want to do something after a task is deleted in this method, use deleteCompletionHandler. After this method returns, deleteCompletionHandler is reset to nil.

    Declaration

    Swift

    public func deleteAllTasks(_ keepFinishedFile: Bool = false) -> Dictionary<String, IndexPath>?

    Parameters

    keepFinishedFile

    Just aim at finished task whose file is downloaded completely, if file is not downloaded completely, even this value is True, temporary file still will be deleted. If this value is false, regardless of task’s download progress, record and relative file will be deleted both. The default is false. You can get file location by fileURL(forTask:) before calling this method.

    Return Value

    A Dictionary of deleted task info. Key: URL string of the deleted task, Value: task original location in downloadList. If no task is deleted, return nil.

  • Delete all files but keep records. If data is not loaded, this method will wait.

    If you want to do something after a task is deleted in this method, use deleteCompletionHandler. After this method returns, deleteCompletionHandler is reset to nil.

    Declaration

    Swift

    public func deleteFilesOfAllTasks() -> [String]?

    Return Value

    An array of URL string of tasks whose file are deleted successfully. If no file is deleted, return nil.

  • A Boolean value that determines whether download manager should download files over a cellular network.

    The default value is false.

    Declaration

    Swift

    public var allowsCellularAccess: Bool = false
  • The maximum count of task that could download at the same time.

    Reducing it will pause redundant downloading tasks automatically; increasing it will resume tasks which are paused in reducing maxDownloadCount.

    The defalut value is OperationQueue.defaultMaxConcurrentOperationCount, which means no limit. Assign a nagative or 0 to this property, this property is set to OperationQueue.defaultMaxConcurrentOperationCount directly.

    Declaration

    Swift

    dynamic public var maxDownloadCount: Int
  • A Boolean value determining that how download manager pause a download task. SDEDownloadManager use NSURLSessionDownloadTask to download file, calling suspend() or cancel(byProducingResumeData:) on NSURLSessionDownloadTask has same results for users: they both pause the download.

    If true, call suspend(); if false, call cancel(byProducingResumeData:). The default value is true. This option won’t be saved.

    Declaration

    Swift

    public var pauseDownloadBySuspendingSessionTask: Bool = true
  • A Boolean value indicating that whether download manager start to download immediately after add a new download task if it has not reach maxDownloadCount. The default value is true. This option won’t be saved.

    Declaration

    Swift

    public var downloadNewFileImmediately: Bool = true
  • A Boolean value determining whether move the task to toDeleteList when delete it. If true, task to delete will be moved to the trash first; if false, delete the task directly.

    Declaration

    Swift

    public var isTrashOpened: Bool = false
  • A closure to execute after a task is deleted. Paratmeters in closure:

    String: URL string of deleted task.

    IndexPath: Deleted task’s location in downloadList or toDeleteList. This parameter should be ignored when only task’s file is deleted in these methods: deleteFilesOfTasks(_:), deleteFilesOfTasks(at:) and deleteFilesOfAllTasks() .

    Int: Count of all tasks to delete.

    Int: The Nth deleted task. Starts from 1.

    Declaration

    Swift

    public var deleteCompletionHandler: ((String, IndexPath, Int, Int) -> Void)? = nil
  • A Boolean value determining whether split download list into groups by their alphanumeric order when sorting by file name. This property is used to switch on/off a feature: section index titles. If false, download list won’t be splited into groups. Works only when sortType == .fileName. The default value is false.

    Declaration

    Swift

    public var indexingFileNameList: Bool = false
  • A Boolean value determining whether split download list into groups when sorting by add time, like: Today, Yesterday, Last 7 Days, Last 30 Days, Older. If false, download list won’t be splited into groups. Works only when sortType == .addTime. The default value is false.

    Declaration

    Swift

    public var sectioningAddTimeList: Bool = false
  • A Boolean value determining whether split download list into groups when sorting by file size, like: 0 ~ 1 MB, 1 MB ~ 10 MB, 10MB ~ 100 MB, 100 MB ~ 1 GB, Larger Than 1 GB. If false, download list won’t be splited into groups. Works only when sortType == .fileSize. The default value is false.

    Declaration

    Swift

    public var sectioningFileSizeList: Bool = false
  • A Boolean value determining whether display name returned by fileDisplayName(ofTask:) and fileDisplayName(at:) hidden its file extension if it has a file extension. The default vale is true.

    Declaration

    Swift

    public var hiddenFileExtension: Bool = true
  • This closure provides download activity info. The default value is nil.

    beginTrackingDownloadActivity() executes this closure every second in the background until there is no more download or call stopTrackingDownloadActivity() to stop it. If there is no more download activity, downloadCompletionHandler will be executed.

    In DownloadListController, this closure is set to update download activity in view.

    Dictionary’s key is download URL string, and value is a tuple include task’s download activity info.

    • receivedBytes: downloaded bytes for now.

    • expectedBytes: file size by bytes. Sometimes it’s negative number, means unknown size.

    • speed: downloaded bytes in last second. This value is -1 if download is over, you should remove speed info in your view at this time.

    • detailInfo: additional information. Usually it’s nil, unless speed == -1(it means download is over). If this value is not nil, it most be format string of download progress, for example: if task is paused, this value could be 41.6 MB/402.5 MB; if task is finished, this value could be 402.5 MB.

    Declaration

    Swift

    public var downloadActivityHandler: ((Dictionary<String, (receivedBytes: Int64, expectedBytes: Int64, speed: Int64, detailInfo: String?)>) -> Void)?
  • Alternate for downloadActivityHandler in Objective-C code. This closure provides download activity info. The default value is nil.

    beginTrackingDownloadActivity() executes this closure every second in the background until there is no more download or call stopTrackingDownloadActivity() to stop it. If there is no more download activity, downloadCompletionHandler will be executed.

    This property is Objective-C version of downloadActivityHandler which can’t be seen in Objective-C file.

    Dictionary’s key is download URL string, and the value is a dictionary include this task’s download activity info, key and value:

    • key: receivedBytes, value type: Int64, downloaded bytes for now.
    • key: expectedBytes, value type: Int64, file size by bytes. Sometimes it’s negative number, means unknown size.
    • key: speed, value type: Int64, downloaded bytes in last second. This value is -1 if download is over, you should remove speed info in your view at this time.
    • key: detailInfo, value type: String, additional information, usually this key-value is not existed, unless speed == -1(it means download is over). Most time it is format string of download progress, for example: if task is paused, this value could be 41.6 MB/402.5 MB; if task is finished, this value could be 402.5 MB.

    Declaration

    Swift

    public var objcDownloadActivityHandler: ((Dictionary<String, Dictionary<String, Any>>) -> Void)?
  • The closure to execute after all downloads are over. It won’t be executed if stopTrackingDownloadActivity() is called. Specially, if all downloading tasks are paused, this closure will be executed also.

    Declaration

    Swift

    public var downloadCompletionHandler: (() -> Void)?
  • A closure to execute after any task is successful or failed(not include cancelling task and stopping task). The default is nil. If you specify handler for special task in download(_:successOrFailHandler:) or resumeTasks(_:successOrFailHandler:), this closure won’t be executed for the special task.

    Closure parameters fileLocation and error, only one is not nil at the same time.

    Declaration

    Swift

    public var taskSuccessOrFailHandler: ((_ URLString: String, _ fileLocation: URL?, _ error: NSError?) -> Void)?

    Parameters

    URLString

    The download URL string of file.

    fileLocation

    File location. It’s not nil only when file is downloaded successfully.

    error

    It’s not nil only when download is failed.

  • A closure to execute in session delegate method: URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:. The default value is nil. Although SDEDownloadManager provides download activity track feature, you still could use this closure to implement this target.

    Declaration

    Swift

    public var downloadTaskWriteDataHandler: ((_ session: URLSession, _ downloadTask: URLSessionDownloadTask, _ bytesWritten: Int64, _ totalBytesWritten: Int64, _ totalBytesExpectedToWrite: Int64) -> Void)?
  • A closure to execute in session delegate method: URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:. The default value is nil.

    Declaration

    Swift

    public var downloadTaskResumeHandler: ((_ session: URLSession, _ downloadTask: URLSessionDownloadTask, _ didResumeAtOffset: Int64, _ expectedTotalBytes: Int64) -> Void)?
  • A closure to execute in session delegate method: URLSessionDidFinishEventsForBackgroundURLSession:. The default value is nil. Use this closure to push a notification after all tasks are done when app is in the background, or update screenshot in Multitasking Screen. Look for configurateListVC() in this project to see the example.

    Declaration

    Swift

    public var backgroundSessionDidFinishEventsHandler: ((_ session: URLSession) -> Void)?
  • A closure to execute in session delegate method: URLSession:didReceiveChallenge:completionHandler:. The default value is nil. Use this closure to handle session-level authentication.

    Declaration

    Swift

    public var sessionDidReceiveChallengeHandler: ((_ session: URLSession, _ challenge: URLAuthenticationChallenge, _ completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)?
  • A closure to execute in session delegate method: URLSession:task:didReceiveChallenge:completionHandler:.

    The default value is nil. Use this closure to handle non session-level authentication.

    Note: I have handled basic and digest authentication, if authentication type is basic and digest, this closure won’t be executed.

    Declaration

    Swift

    public var taskDidReceiveChallengeHandler: ((_ session: URLSession, _ task: URLSessionTask, _ challenge: URLAuthenticationChallenge, _ completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)?
  • Sort downloadList in place with predefined type or switch sort mode.

    Note: This method’s performance is not good when download list has more than 1000 tasks. When parameter sortType is .fileName and indexingFileNameList == true, its performance is worst.

    Declaration

    Swift

    public func sortListBy(type: ComparisonType, order: ComparisonOrder = .ascending)

    Parameters

    type

    In manual mode, a section in downloadList must has a title, and it will lose all section titles when switching from .manual to other types. And all tasks will be integrated into a single section with a placeholder title when switching from other types to .manual.

    order

    Sort order for tasks in section: .ascending or .descending. The default value is .ascending.

  • Sort downloadlist in place with powerful predicate.

    Object comforms to Sequence has a method sort(by:) to sort list with custom predicate, which is used to implement sortListBy(type:order:), and it also could be used to custom sort in this method, and very powerful, e.g., sortListBy(type: .fileSize, order: .ascending) could be implmented by this method like this:

    dm.sortListBy(order: .ascending, taskAscending: {
        dm.fileByteCount(ofTask: $0) < dm.fileByteCount(ofTask: $1)
    })
    

    sortListBy(type:order:) supports only four predefined sort types because it can’t use unknown info to sort download list. Now you could add other info for task(by fetchMetaInfoHandler) and sort list by it in this method, e.g., you bulit a list of movies with release year, now sort movies by its release year:

    // Just show what this method do, some details are omited.
    dm.sortListBy(order: .descending, taskAscending: {
        let year0 = dm.info(ofTask: $0, about: ReleaseYearKey) as! Int
        let year1 = dm.info(ofTask: $1, about: ReleaseYearKey) as! Int
        return year0 < year1
    })
    

    In above two examples, there is only one section. When sort list with .fileType, tasks are splited into several sections by their file type. Technically, implement way is: filter tasks that have same trait and integrate these tasks into the same section; then sort sections and tasks in section. It likes sorting a Dictionary. What is appropriate trait? How to sort splited sections, based on what? There is an example, sort a list of songs: splited by its singer and singers are sorted by alphabet, singer’s songs are sorted by release year and song name.

    dm.sortListBy(order: .ascending, taskTrait: { URLString in
        // Tasks which return same trait string will be integrated into the same section.
        // Returned trait string is also title for section in `downloadList`.
        // Sections are sorted by trait string in alphabet order.
        // If return nil, task will be in the last section with a placeholder title.
        dm.info(ofTask: URLString, about: SingerKey) as? String
    }, taskAscending: {
        // Sort tasks in section.
        let releaseYear0 = dm.info(ofTask: $0, about: ReleaseYearKey) as? Int
        let releaseYear1 = dm.info(ofTask: $1, about: ReleaseYearKey) as? Int
        let sing0 = dm.fileDisplayName(ofTask: $0)!
        let sing1 = dm.fileDisplayName(ofTask: $1)!
    
        switch (year0, year1){
        case (nil, nil): return sing0 < sing1
        case (nil, _): return true
        case (_, nil): return false
        case (_, _):
            if year0! < year1!{
                return true
            }else if year0! > year1!{
                return false
            }else{
                return sing0 < sing1
            }
        }
    })
    

    Above sections are sorted by trait titles in alphabet order, sometimes it’s not what you want, e.g., I want to sort list by add time but split into sections like this:

    ["Today", "Yesterday", "Last 7 Days", "Last 30 Days", "Older"]
    

    If sort it in in alphabet order, this method will get the following result or reversed:

    ["Last 30 Days", "Last 7 Days", "Older", "Today", "Yesterday"]
    

    Sectin location can be adjusted manually by moveTasks(inSection:to:), but it’s not good way, and it’s getting worse if some titles are not existed. Actually, it’s easy to fix: add another predicate to reorder trait strings created in taskTrait.

    let AddTimeKey = "Key.Date.TaskCreateDate"
    let today = Calendar.current.startOfDay(for: Date())
    let DayInterval: TimeInterval = 24 * 60 * 60
    let traitPriority = ["Today": 0, "Yesterday": -10, "Last 7 Days": -100, "Last 30 Days": -1000, "Older": -10000]
    
    dm.sortListBy(order: .ascending, taskTrait: { URLString in
        // Tasks which have same trait string will be integrated into the same section.
        // Returned trait string is also title for section in `downloadList`.
        // Sections are sorted by trait string with custom predicate `traitAscending`.
        // If return nil, task will be in the last section with a placeholder title.
        let addTime = dm.info(ofTask: URLString, about: AddTimeKey) as! Date
        if Calendar.current.isDateInToday(addTime){
            return "Today"
        }else if Calendar.current.isDateInYesterday(addTime){
            return "Yesterday"
        }else if today.timeIntervalSince(addTime) < 7 * DayInterval{
            return "Last 7 Days"
        }else if today.timeIntervalSince(addTime) < 30 * DayInterval{
            return "Last 30 Days"
        }else{
            return "Older"
        }
    }, traitAscending: {
        // Sort trait strings, and relative section is reordered also.
        traitPriority[$0]! < traitPriority[$1]!
    }, taskAscending: {
        // Sort tasks in section.
        dm.fileDisplayName(ofTask: $0)! < dm.fileDisplayName(ofTask: $1)!
    })
    

    Note: sortType will be set to .manual in this method. I was going to add another sort mode .custom, but there is no benefit except adding complexity.

    Declaration

    Swift

    public func sortListBy(order: ComparisonOrder,
                           taskTrait: ((_ URLString: String) -> String?)? = nil,
                           traitAscending: ((_ trait: String, _ trait: String) -> Bool)? = nil,
                           taskAscending: (_ URLString: String, _ URLString: String) -> Bool)

    Parameters

    order

    Sort order for section and tasks in section: .ascending or .descending.

    taskTrait

    A closure that returns trait string for task. The default value is nil, which means that there will be one section with a placeholder title only. Tasks which have same trait string will be integrated into the same section, and trait string is also section title. If closure returns nil, task will be in the last section with a placeholder title. Sections are sorted by their titles with predicate traitAscending, if traitAscending is nil, sections are sorted by their titles in alphabet order.

    traitAscending

    A predicate that returns true if the first trail string should be ordered before the second trait string; otherwise, false. Trait string is also section title. It’s used to sort section titles returned by taskTrait and relative sections.

    taskAscending

    A predicate that returns true if the first task should be ordered before the second task; otherwise, false. It’s used to sort tasks in section.

  • Move task’s location in downloadList. It’s your responsibility to check indexPath’s validity.

    Precondition

    sortType == .manual

    Declaration

    Swift

    public func moveTask(at indexPath: IndexPath, to newIndexPath: IndexPath)

    Parameters

    indexPath

    Source location.

    newIndexPath

    Destination location.

  • Move a whole section in downloadList. It’s your responsibility to check section’s validity.

    Precondition

    sortType == .manual

    Declaration

    Swift

    public func moveTasks(inSection section: Int, to newSection: Int)

    Parameters

    section

    Source location.

    newSection

    Destionation location.

  • Request a thumbnail with specified height. This method is synchronous.

    If file is not image or video, and you don’t custom thumbnail for it by setCustomThumbnail(_:forTask:), this method returns a type icon. About type icon, you could offer custom icon(must be png file) for specified type by naming image file with file extension’s uppercased, e.g., you want a .psd file to display custom icon, add PSD.png to this library, into /Resource/FileExtensionIcon.xcassets, this method will return an UIImage object inited from PSD.png for all .psd files.

    Declaration

    Swift

    public func requestThumbnail(forTask URLString: String, targetHeight height: CGFloat, orLaterProvidedInHandler thumbnailHandler: @escaping (_ thumbnail: UIImage) -> Void) -> UIImage?

    Parameters

    URLString

    The URL string of task which you want to request thumbnail for.

    height

    The target height of image to return.

    thumbnailHandler

    A closure to provide fetched thumbnail. This closure will be called only when: 1. no cache when calling this method; 2. thumbnail is created successfully.

    thumbnail

    Thumbnail image for the request. And you will find image height is not exactly requested height sometimes, but its width is. It’s adapted for DownloadListController.

    Return Value

    A thumbnail if it’s in the cache, otherwise a type icon. Return nil if URLString is not in the list.

  • Remove all thumbnails.

    Declaration

    Swift

    public func emptyThumbnailCache()
  • Custom thumbnail for the task, except for image file.

    Precondition

    File is not a image.

    Declaration

    Swift

    public func setCustomThumbnail(_ thumbnail: UIImage, forTask URLString: String, cacheInMemoryOnly: Bool)

    Parameters

    thumbnail

    Image to used as thumbnail.

    URLString

    The URL string of task which you want to custom thumbnail for.

    cacheInMemoryOnly

    If false, thumbnail will be stored. If multiple files need a same thumbail, e.g., an album art for songs, caching it in memory only could reduce memory usage.

  • Remove custom thumbnail for the task and return it.

    Declaration

    Swift

    public func removeCustomThumbnailForTask(_ URLString: String) -> UIImage?

    Parameters

    URLString

    The URL string of task whose custom thumbnail you want to remove.

    Return Value

    Return the image which is used as thumbnail for the task. Return nil if no custom thumbnail.

  • Clean up to-delete tasks in toDeleteList and return a Dictionary includes deleted task’s URL string and its location info.

    Declaration

    Swift

    public func cleanupToDeleteTasks(_ URLStrings: [String]) -> Dictionary<String, IndexPath>?

    Parameters

    URLStrings

    An array of download URL string of task which you want to clean up in toDeleteList.

    Return Value

    A Dictionary includes deleted task info. Key: URL string of deleted task, Value: task original location in toDeleteList as a IndexPath with section 0, it is to be used in UITableView/UICollectionView directly. If no task is deleted, return nil.

  • Clean up all to-delete tasks in toDeleteList and return a Dictionary includes deleted task’s URL string and its location info..

    Declaration

    Swift

    public func emptyToDeleteList() -> Dictionary<String, IndexPath>?

    Return Value

    A Dictionary includes cleaned task info. Key: URL string of cleaned task, Value: task original location in toDeleteList as a IndexPath with section 0, it is to be used in UITableView/UICollectionView directly. If no task is deleted, return nil.

  • Restore to-delete tasks in toDeleteList back to downloadList and return locations of restored deleted tasks in toDeleteList.

    Declaration

    Swift

    public func restoreToDeleteTasks(_ URLStrings: [String], toLocation indexPath: IndexPath = IndexPath(row: 0, section: 0)) -> [IndexPath]?

    Parameters

    URLStrings

    An array of download URL string of task which you want to restore in toDeleteList. If sortType == .manual, restored tasks keeps same orders in this parameter.

    indexPath

    Restore location in downloadList. If sortType != .manual, this paramter is ignored. It’s your resposibility to check whether location is valid.

    Return Value

    Original locations of restored tasks in toDeleteList, or nil no task is restored. Returned value, [IndexPath], not [Int], is to be used in UITableView/UICollectionView directly.

  • Restore all to-delete tasks in toDeleteList back to downloadList and return locations of restored deleted tasks in toDeleteList.

    Declaration

    Swift

    public func restoreAllToDeleteTasks(toLocation indexPath: IndexPath = IndexPath(row: 0, section: 0)) -> [IndexPath]?

    Parameters

    indexPath

    The restore location in downloadList. If sortType != .manual, this paramter is ignored. It’s your resposibility to check whether location is valid. The default value is (0, 0).

    Return Value

    The locations of restored tasks in toDeleteList. If no task is restored, return nil. Returned value, [IndexPath], not [Int], is to be used in UITableView/UICollectionView directly.

  • The hash value.

    Declaration

    Swift

    override open var hash: Int
  • ==

    Declaration

    Swift

    override open func isEqual(_ object: Any?) -> Bool
  • Reserved key for outer to store file name in meta info. More details in SDEDownloadManager‘s fetchMetaInfoHandler.

    Declaration

    Swift

    public static let TIFileDisplayNameStringKey: String = "Key.String.FileDisplayName"
  • Reserved key for outer to store file intro in meta info. More details in SDEDownloadManager‘s fetchMetaInfoHandler.

    Declaration

    Swift

    public static let TIFileIntroStringKey: String = "Key.String.FileIntro"
  • Update or add meta info for download task.

    Declaration

    Swift

    public func updateMetaInfo(_ info: Dictionary<String, Any>, forTask URLString: String)

    Parameters

    info

    Meta info to update. Its value should be property list type, otherwise it can’t be saved. In Swift, all relative primitive value types are compatible, like: String, Data, Date, Bool, all integer types(e.g., Int, Int8, UInt32), all floating-point types(e.g., Float, Double, CGFloat, except for Float80), for collectiontypes, Array and Dictionary consist of these primitive value types are OK.

    URLString

    The download URL string of the task which you want to update.

  • The notification is posted for any interrupted download task in download manager when app is forcely quited and relanched again. Task’s download info is changed, which can be get from downloadDetail(ofTask:).

    Get the only value in notification info, task URL string: notification.userInfo?["URLString"] as? String.

    Declaration

    Swift

    public static let NNRestoreFromAppForceQuit: Notification.Name = Notification.Name(rawValue: "RestoreFromAppForceQuitNotification")
  • The notification is posted for task which changed display name. Task’s display name can be get from fileDisplayName(ofTask:).

    Get the only value in notification info, task URL string: notification.userInfo?["URLString"] as? String.

    Declaration

    Swift

    public static let NNChangeFileDisplayName: Notification.Name = Notification.Name(rawValue: "ChangeFileDisplayNameNotification")
  • The notification is posted for task whose file is downloaded before download manager begin to track. Task’s download info is changed, which can be get from downloadDetail(ofTask:).

    Get the only value in notification info, task URL string: notification.userInfo?["URLString"] as? String.

    Declaration

    Swift

    public static let NNDownloadIsCompletedBeforeTrack: Notification.Name = Notification.Name(rawValue: "DownloadIsCompletedBeforeTrackNotification")
  • The notification is posted for task whose downloaded temporary file is processing. Task’s download info is changed, which can be get from downloadDetail(ofTask:).

    Get the only value in notification info, task URL string: notification.userInfo?["URLString"] as? String.

    Declaration

    Swift

    public static let NNTemporaryFileIsProcessing: Notification.Name = Notification.Name(rawValue: "TemporaryFileIsProcessingNotification")
  • The notification is posted for task whose downloaded temporary file has been processed. Task’s download info is changed, which can be get from downloadDetail(ofTask:).

    Get the only value in notification info, task URL string: notification.userInfo?["URLString"] as? String.

    Declaration

    Swift

    public static let NNTemporaryFileIsProcessed: Notification.Name = Notification.Name(rawValue: "TemporaryFileIsProcessedNotification")
  • Get the location of download task in downloadList based on its download URL string.

    Declaration

    Swift

    public subscript(URLString: String) -> IndexPath?

    Parameters

    URLString

    The download URL string.

    Return Value

    An index path representing task location in downloadList, or nil if it’s not in downloadList.

  • Get the URL string of download task based on its location in downloadList.

    Declaration

    Swift

    @nonobjc public subscript(indexPath: IndexPath) -> String?

    Parameters

    indexPath

    Location in downloadList, which is a two-dimensional string array: [[String]].

    Return Value

    The URL string at the location in downloadList, or nil if location is beyond the bounds.

  • Resume(continue) tasks at specified locations and return locations of tasks which are resumed successfully.

    Declaration

    Swift

    public func resumeTasks(at indexPaths: [IndexPath]) -> [IndexPath]?

    Parameters

    indexPaths

    Task locations in downloadList.

    Return Value

    Locations of tasks which are resumed successfully. If no task is resumed, return nil.

  • Pause tasks at specified locations and return locations of tasks which are paused successfully.

    If pauseDownloadBySuspendingSessionTask == true, it suspends the relative NSURLSessionDownloadTask object; otherwise, stop it by ‘cancel(byProducingResumeData:)’, they are same results for users.

    Declaration

    Swift

    public func pauseTasks(at indexPaths: [IndexPath]) -> [IndexPath]?

    Parameters

    indexPaths

    Task locations in downloadList.

    Return Value

    Locations of tasks which are paused successfully. If no task is paused, return nil.

  • Stop tasks at specified locations and return locations of tasks which are stopped successfully.

    Declaration

    Swift

    public func stopTasks(at indexPaths: [IndexPath]) -> [IndexPath]?

    Parameters

    indexPaths

    Task locations in downloadList.

    Return Value

    Locations of tasks which are stopped successfully. If no task is stopped, return nil.

  • Delete tasks at specified locations and return a Dictionary includes deleted task’s URL string and its original location in downloadList. If data is not loaded, this method will wait.

    If isTrashOpened == true, tasks will be moved to toDeleteList.

    If you want to do something after a task is deleted in this method, use deleteCompletionHandler. After this method returns, deleteCompletionHandler is reset to nil.

    Declaration

    Swift

    public func deleteTasks(at indexPaths: [IndexPath], keepFinishedFile: Bool = false) -> Dictionary<String, IndexPath>?

    Parameters

    indexPaths

    Task locations in downloadList.

    keepFinishedFile

    Just works for finished task whose file is downloaded completely. For task whose state is not finished, this parameter is ignored. The default value is false. You can get file location by fileURL(ofTask:) -> URL? before calling this method.

    Return Value

    A Dictionary includes info of deleted tasks. Key: URL string of deleted task, Value: task original location in downloadList. Return nil if no task is deleted.

  • Delete file only and keep task record, and return locations of tasks whose file are deleted successfully. If data is not loaded, this method will wait.

    Relative file will be deleted no matter whether file is downloaded completely or not.

    Specially, if task’s state is .pending, it’s also included in returned result.

    If you want to do something after a task is deleted in this method, use deleteCompletionHandler. After this method returns, deleteCompletionHandler is reset to nil.

    Declaration

    Swift

    public func deleteFilesOfTasks(at indexPaths: [IndexPath]) -> [IndexPath]?

    Parameters

    indexPaths

    Task locations in downloadList.

    Return Value

    Locations of tasks whose file are deleted, or nil if no file is deleted.

  • Redownload files of tasks at the specified locations if task is finished or stopped, and return locations of tasks which are restarted successfully. The downloaded file will be deleted before restart.

    Declaration

    Swift

    public func restartTasks(at indexPaths: [IndexPath]) -> [IndexPath]?

    Parameters

    indexPaths

    Task locations in downloadList.

    Return Value

    Locations of tasks which are restarted successfully, or nil if no task is restarted.

  • Resume(continue) tasks in specified section and return locations of tasks which are resumed successfully.

    Declaration

    Swift

    public func resumeTasksInSection(_ section: Int) -> [IndexPath]?

    Parameters

    section

    The section index in downloadList. If it’s beyond the bounds, return nil.

    Return Value

    Locations of tasks which are resumed successfully. If no task is resumed, return nil.

  • Pause tasks in specified section and return locations of tasks which are paused successfully.

    If pauseDownloadBySuspendingSessionTask == true, it suspends the relative NSURLSessionDownloadTask object; otherwise, stop it by ‘cancel(byProducingResumeData:)’, they are same results for users.

    Declaration

    Swift

    public func pauseTasksInSection(_ section: Int) -> [IndexPath]?

    Parameters

    section

    The section index in downloadList. If it’s beyond the bounds, return nil.

    Return Value

    Locations of tasks which are paused successfully. If no task is paused, return nil.

  • Stop tasks in specified section and return locations of tasks which are stopped successfully.

    Declaration

    Swift

    public func stopTasksInSection(_ section: Int) -> [IndexPath]?

    Parameters

    section

    The section index in downloadList. If it’s beyond the bounds, return nil.

    Return Value

    Locations of tasks which are stopped successfully. If no task is stopped, return nil.

  • Delete tasks in specified section and return a Dictionary includes deleted task’s URL string and its original location in downloadList. If data is not loaded, this method will wait.

    If isTrashOpened == true, tasks will be moved to toDeleteList.

    If you want to do something after a task is deleted in this method, use deleteCompletionHandler. After this method returns, deleteCompletionHandler is reset to nil.

    Declaration

    Swift

    public func deleteTasksInSection(_ section: Int, keepFinishedFile: Bool = false) -> Dictionary<String, IndexPath>?

    Parameters

    section

    The section index in downloadList. If it’s beyond the bounds, return nil.

    keepFinishedFile

    Just works for finished task whose file is downloaded completely. For task whose state is not finished, this parameter is ignored. The default value is false. You can get file location by fileURL(ofTask:) -> URL? before calling this method.

    Return Value

    A Dictionary includes info of deleted tasks. Key: URL string of deleted task, Value: task original location in downloadList. Return nil if no task is deleted.

  • Delete file only and keep task record, and return locations of tasks whose file are deleted successfully. If data is not loaded, this method will wait.

    Relative file will be deleted no matter whether file is downloaded completely or not.

    If you want to do something after a task is deleted in this method, use deleteCompletionHandler. After this method returns, deleteCompletionHandler is reset to nil.

    Declaration

    Swift

    public func deleteFilesOfTasksInSection(_ section: Int) -> [IndexPath]?

    Parameters

    section

    The section index in downloadList. If it’s beyond the bounds, return nil.

    Return Value

    Locations of tasks whose file are deleted, or nil if no file is deleted.

  • Redownload files of tasks in specified section if task is finished or stopped, and return locations of tasks which are restarted successfully. The downloaded file will be deleted before restart.

    Declaration

    Swift

    public func restartTasksInSection(_ section: Int) -> [IndexPath]?

    Parameters

    section

    The section index in downloadList. If it’s beyond the bounds, return nil.

    Return Value

    Locations of tasks which are restarted successfully, or nil if no task is restarted.

  • Clean up to-delete tasks in toDeleteList at specified locations, and return a Dictionary includes deleted task’s URL string and its location info.

    If you want to do something after a task is deleted in this method, use deleteCompletionHandler. After this method returns, deleteCompletionHandler is reset to nil.

    Declaration

    Swift

    public func cleanupToDeleteTasks(at indexes: [Int]) -> Dictionary<String, IndexPath>?

    Parameters

    indexes

    An array of index location of to-delete task in toDeleteList. If you have an IndexSet, pass it as Array(indexSet); if you have an array of IndexPath, pass it as indexPaths.map({$0.row}).

    Return Value

    A Dictionary includes deleted task info. Key: URL string of deleted task, Value: task original location in toDeleteList as a IndexPath with section 0, it is to be used in UITableView/UICollectionView directly. If no task is deleted, return nil.

  • Clean up to-delete tasks in toDeleteList in specified continuous range, and return a Dictionary includes deleted task’s URL string and its location info..

    If you want to do something after a task is deleted in this method, use deleteCompletionHandler. After this method returns, deleteCompletionHandler is reset to nil.

    Declaration

    Swift

    public func cleanupToDeleteTasks(from startIndex: Int, to endIndex: Int = Int.max) -> Dictionary<String, IndexPath>?

    Parameters

    startIndex

    The start index of range to clean up. It can’t be small than 0.

    endIndex

    The end index of range to clean up. This value is loose. If it’s beyonds the bound, this method cleans up from start index to list tail. It can’t be small than startIndex.

    Return Value

    A Dictionary includes deleted task info. Key: URL string of deleted task, Value: task original location in toDeleteList as a IndexPath with section 0, it is to be used in UITableView/UICollectionView directly. If no task is deleted, return nil.

  • Restore to-delete tasks in toDeleteList at specified locations back to downloadList and return original locations of restored tasks in toDeleteList.

    Declaration

    Swift

    public func restoreToDeleteTasks(at indexes: [Int], toLocation indexPath: IndexPath = IndexPath(row: 0, section: 0)) -> [IndexPath]?

    Parameters

    indexes

    An array of index location of to-delete task in toDeleteList. If you have an IndexSet, pass it as Array(indexSet); if you have an array of IndexPath, pass it as indexPaths.map({$0.row}).

    indexPath

    Restore location in downloadList. If sortType != .manual, this paramter is ignored. It’s your resposibility to check whether location is valid.

    Return Value

    Original locations of restored tasks in toDeleteList, or nil if no task is restored. Returned value, [IndexPath], not [Int], is to be used in UITableView/UICollectionView directly

  • Change file display name.

    Precondition

    Task is not in toDeleteList.

    Declaration

    Swift

    public func changeDisplayNameOfTask(_ URLString: String, to newDisplayName: String)

    Parameters

    URLString

    The URL string of task which you want to change.

    newDisplayName

    New Name. It can’t be empty string.

  • Change section title in manual mode.

    Precondition

    sortType == .manual.

    Declaration

    Swift

    public func changeTitleOfSection(_ section: Int, to newTitle: String)

    Parameters

    section

    The section which you want to change.

    newTitle

    New title used in the header view.

  • Query download task’s location in downloadList.

    Declaration

    Swift

    public func indexPath(ofTask URLString: String) -> IndexPath?

    Parameters

    URLString

    The download URL string of task.

    Return Value

    An index path representing task location in downloadList, or nil if it’s not in downloadList(but it maybe in toDeleteList).

  • Query info of download task.

    Declaration

    Swift

    public func info(ofTask URLString: String) -> Dictionary<String, Any>?

    Parameters

    URLString

    The download URL string of task.

    Return Value

    A dictionary includes task information, or nil if URLString is not in the download manager.

  • Query specified info about download task. This method is designed to query info which is added from outer by fetchMetaInfoHandler.

    Declaration

    Swift

    public func info(ofTask URLString: String, about key: String) -> Any?

    Parameters

    URLString

    The download URL string of task.

    key

    A string of key to query.

    Return Value

    Relavtive info. You must known which type it is.

  • Query download task state.

    Declaration

    Swift

    public func downloadState(ofTask URLString: String) -> DownloadState

    Parameters

    URLString

    The download URL string of task.

    Return Value

    An enum value which indicates download task state.

  • Query the display name of file in the download task. If hiddenFileExtension == true, returned string doesn’t include file extension.

    Declaration

    Swift

    public func fileDisplayName(ofTask URLString: String) -> String?

    Parameters

    URLString

    The download URL string of task.

    Return Value

    A string, or nil if URLString is not in download manager. Most time it’s file name, it’s maybe URL string self if file name can’t be fetched.

  • Query download progress([0, 1]). If task is downloading, value returned by this method is not right. How to get realtime progress when downloading? The answer is property downloadActivityHandler.

    Declaration

    Swift

    public func downloadProgress(ofTask URLString: String) -> Float

    Parameters

    URLString

    The download URL string of task.

    Return Value

    A float value in 0.0...1.0. Specially, return -1 if URLString is not in the download manger; return 0 if progress is unknown.

  • Query file size by byte count.

    Declaration

    Swift

    public func fileByteCount(ofTask URLString: String) -> Int64

    Parameters

    URLString

    The download URL string of task.

    Return Value

    A Int64 value representing file byte count. Specially, return -1 if URLStrig is not in the download manager, or file size is unknown.

  • Query local path of downloaded file.

    Declaration

    Swift

    public func filePath(ofTask URLString: String) -> String?

    Parameters

    URLString

    The download URL string of task.

    Return Value

    An absolute path string(start with /) if file is downloaded already, otherwise nil.

  • Query local path of downloaded file by URL.

    Declaration

    Swift

    public func fileURL(ofTask URLString: String) -> URL?

    Parameters

    URLString

    The download URL string of task.

    Return Value

    A file URL if file is downloaded already; otherwise nil.

  • Query detail about download activity.

    Sometimes it’s error info. And most times this method return task’s download progress info: if task is not finished, return a string of (downloadedSize)/(fileSize); if finished, return a string of (fileSize).

    Note: This method returns nil if task is downloading, you can fetch it in downloadActivityHandler.

    Declaration

    Swift

    open func downloadDetail(ofTask URLString: String) -> String?

    Parameters

    URLString

    The download URL string of task.

    Return Value

    A string describing download activity, or nil if URLString is not in the download manager or task is downloading.

  • Query file type. Predefined types: Image, Audio, Video, Document, Other.

    Declaration

    Swift

    public func fileType(ofTask URLString: String) -> String?

    Parameters

    URLString

    The download URL string of task.

    Return Value

    A string describing file type, or nil if URLString is not in the download manager.

  • Check whether downloaded file is existed.

    Declaration

    Swift

    public func isFileExisted(ofTask URLString: String) -> Bool

    Parameters

    URLString

    The download URL string of task.

    Return Value

    Return true only if task is finished and file is existed, otherwise false.

  • Query the URL string of download task at specified location.

    Declaration

    Swift

    public func downloadURLString(at indexPath: IndexPath) -> String?

    Parameters

    indexPath

    Task location in downloadList.

    Return Value

    A URL string, or nil if indexPath is beyond the bounds.

  • Query download task state.

    Declaration

    Swift

    public func downloadState(at indexPath: IndexPath) -> DownloadState

    Parameters

    indexPath

    Task location in downloadList.

    Return Value

    An enum value which indicates task state.

  • Query display name of file in the download task. If hiddenFileExtension == true, returned string doesn’t include file extension.

    Declaration

    Swift

    public func fileDisplayName(at indexPath: IndexPath) -> String?

    Parameters

    indexPath

    Task location in downloadList.

    Return Value

    A string, or nil if indexPath is beyond the bounds. Most time it’s file name, maybe URL string if can’t fetch file name from URL.

  • Query download progress([0, 1]). If task is downloading, value returned by this method is not right. How to get realtime progress when downloading? The answer is property downloadActivityHandler.

    Declaration

    Swift

    public func downloadProgress(at indexPath: IndexPath) -> Float

    Parameters

    indexPath

    Task location in downloadList.

    Return Value

    A Float value in 0.0...1.0. Specially, return -1 if indexPath is beyond the bounds; return 0 if progress is unknown.

  • Query file size by byte count.

    Declaration

    Swift

    public func fileByteCount(at indexPath: IndexPath) -> Int64

    Parameters

    indexPath

    Task location in downloadList.

    Return Value

    An Int64 value. Specially, return -1 if indexPath is beyond the bounds or it’s unknown.

  • Query downloaded file’s absolute path.

    Declaration

    Swift

    public func filePath(at indexPath: IndexPath) -> String?

    Parameters

    indexPath

    Task location in downloadList.

    Return Value

    An absolute path string(start with /) if file is downloaded already, otherwise nil.

  • Query downloaded file’s absolute path by URL.

    Declaration

    Swift

    public func fileURL(at indexPath: IndexPath) -> URL?

    Parameters

    indexPath

    Task location in downloadList.

    Return Value

    A file URL if file is downloaded already, otherwise nil.

  • Query detail about download activity.

    Sometimes it’s error info. And most times this method return task’s download progress info: if task is not finished, return a string of (downloadedSize)/(fileSize); if finished, return a string of (fileSize).

    Note: This method returns nil if task is downloading, you can fetch it in downloadActivityHandler.

    Declaration

    Swift

    public func downloadDetail(at indexPath: IndexPath) -> String?

    Parameters

    indexPath

    Task location in downloadList.

    Return Value

    A String describing download activity, or nil if location is beyond the bounds or task is downloading.

  • Query file type. Predefined types: Image, Audio, Video, Document, Other.

    Declaration

    Swift

    public func fileType(at indexPath: IndexPath) -> String?

    Parameters

    indexPath

    Task location in downloadList.

    Return Value

    A string describing file type, or nil if location is beyond the bounds.

  • Debug method to reproduce download data with random create date and file size. If the count of existed tasks is larger than specified count, this method will reduce it to target count.

    Declaration

    Swift

    public func reproduceDataToCount(_ count: Int)

    Parameters

    count

    The target count of records in downloadTaskSet.

  • Print task info. You should custom code to print info you want.

    Declaration

    Swift

    public func printInfoForTask(_ task: String)