Last active
September 22, 2017 20:51
-
-
Save Natata/7fa43db6ec936b3a840d0e7231fbcfa3 to your computer and use it in GitHub Desktop.
Alamofire-based downloader used to download file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Downloader.swift | |
// | |
// Created by Natata on 2017/9/15. | |
// Copyright © 2017 Natata. All rights reserved. | |
// | |
import Foundation | |
import Alamofire | |
protocol DownloaderDelegate { | |
func updateProgress(completed: Double) | |
} | |
class Downloader { | |
let urlString: String | |
let fileName: String | |
var delegate: DownloaderDelegate? | |
var completion: ((String) -> Void)? | |
var downloadRequest: DownloadRequest? | |
var destination: DownloadRequest.DownloadFileDestination? | |
var isPaused: Bool = false | |
var resumeData: Data? | |
init(urlString: String, fileName: String, completion: ((String) -> Void)?) { | |
self.urlString = urlString | |
self.fileName = fileName | |
self.completion = completion | |
self.destination = {_, _ in | |
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] | |
let destinationURL = documentsURL.appendingPathComponent(fileName, isDirectory: false) | |
return (destinationURL, [.removePreviousFile, .createIntermediateDirectories]) | |
} | |
} | |
func resume() { | |
self.isPaused = false | |
if let resumeData = resumeData { | |
print("redownload from resume data") | |
downloadRequest = Alamofire.download(resumingWith: resumeData, to: destination) | |
} else if let downloadRequest = downloadRequest { | |
print("resume") | |
downloadRequest.resume() | |
} else { | |
downloadRequest = Alamofire.download(self.urlString, to: destination) | |
} | |
setDownloadRequest() | |
} | |
func pause() { | |
self.isPaused = true | |
if let downloadRequest = downloadRequest { | |
print("paused") | |
downloadRequest.suspend() | |
} | |
} | |
func cancel() { | |
self.isPaused = true | |
if let downloadRequest = downloadRequest { | |
print("cancel") | |
downloadRequest.cancel() | |
resumeData = downloadRequest.resumeData | |
} | |
} | |
func setDownloadRequest() { | |
downloadRequest?.downloadProgress { progress in | |
self.delegate?.updateProgress(completed: progress.fractionCompleted) | |
}.response { response in | |
print("[Download] complete response: \(response)") | |
if response.error == nil, | |
let path = response.destinationURL?.path { | |
self.completion?(path) | |
} else { | |
print("[Download] error happended: \(response.error?.localizedDescription))") | |
self.resumeData = response.resumeData | |
} | |
} | |
} | |
} |
Author
Natata
commented
Sep 15, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment