Skip to content

Instantly share code, notes, and snippets.

@Natata
Last active September 22, 2017 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Natata/7fa43db6ec936b3a840d0e7231fbcfa3 to your computer and use it in GitHub Desktop.
Save Natata/7fa43db6ec936b3a840d0e7231fbcfa3 to your computer and use it in GitHub Desktop.
Alamofire-based downloader used to download file
//
// 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
}
}
}
}
@Natata
Copy link
Author

Natata commented Sep 15, 2017

let downloader = Downloader(urlString: "https://httpbin.org/image/png", fileName: "pig.png") { (filePath) in
    print(filePath)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment