Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Alamofire
- typealias DownloadOptions = DownloadRequest.DownloadOptions
- typealias DownloadDestination = DownloadRequest.DownloadFileDestination
- typealias DownloadingProgressHandler = (_ completedUnitCount: Int64, _ totalUnitCount: Int64) -> Void
- typealias DownloadingEndHandler = (_ success: Bool, _ destination: URL?, _ fileName: String?) -> Void
- protocol Downloadable: Hashable {
- var downloadURL: String! { get }
- var downloadDestination: DownloadDestination? { get }
- var acceptableMIMETypes: [String] { get }
- }
- func ==<T: Downloadable>(lhs: T, rhs: T) -> Bool {
- return lhs.hashValue == rhs.hashValue
- }
- class DownloadsManager: Alamofire.SessionManager {
- static let sharedManager = DownloadsManager()
- private(set) var downloads: Dictionary<Int, APIRequest> = [:]
- private init(){
- let configuration = URLSessionConfiguration.background(withIdentifier: "com.earlyaccess.apps.YaBeam.background")
- configuration.timeoutIntervalForRequest = 30
- super.init(configuration: configuration)
- }
- @discardableResult func download<T: Downloadable>(entity: T!, progressHandler: DownloadingProgressHandler? = nil, endHandler: DownloadingEndHandler? = nil) -> APIRequest {
- if let request = downloads[entity.hashValue] {
- request.cancel()
- }
- let finalDestination: DownloadDestination = entity.downloadDestination != nil ? entity.downloadDestination! : { (url, response) in
- let fileManager = FileManager.default
- let directoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
- let pathComponent = response.suggestedFilename ?? ""
- return (directoryURL.appendingPathComponent(pathComponent), DownloadOptions.removePreviousFile)
- }
- let destination: DownloadDestination = { (url, response) in
- let destination = finalDestination(url, response)
- if FileManager.default.fileExists(atPath: destination.destinationURL.path) {
- do {
- try FileManager.default.removeItem(atPath: destination.destinationURL.path)
- } catch {}
- }
- return (destination.destinationURL, DownloadOptions.removePreviousFile)
- }
- return download(entity.downloadURL, to: destination)
- .downloadProgress { (progress) in
- progressHandler?(progress.completedUnitCount, progress.totalUnitCount)
- }
- .response(completionHandler: { (response) in
- var failed = false
- if response.error != nil ||
- response.response?.statusCode != 200 ||
- (entity.acceptableMIMETypes.isNotEmpty && !entity.acceptableMIMETypes.contains(response.response?.mimeType ?? "")) {
- failed = true
- }
- var destinationURL: URL? = nil
- var fileName: String? = nil
- if let temporaryURL = response.temporaryURL, let _response = response.response {
- destinationURL = finalDestination(temporaryURL, _response).destinationURL
- fileName = destinationURL?.lastPathComponent
- }
- endHandler?(!failed, destinationURL, fileName)
- })
- }
- }
Add Comment
Please, Sign In to add comment