-
Notifications
You must be signed in to change notification settings - Fork 0
/
ViewController+downloadable.swift
67 lines (61 loc) · 2.69 KB
/
ViewController+downloadable.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//
// ViewController+downloadable.swift
// EpubBookReader
//
// Created by Amr Elghadban on 27/11/2022.
// Copyright © 2022 ADKA Tech. All rights reserved.
// www.adkatech.com
//
import Foundation
import Alamofire
typealias ResultResponse<T> = ((Result<T, Error>) -> Void)
extension ViewController {
func download(_ urlString: String, fileName: String, folderDirName: String, completion: @escaping ResultResponse<Any>) {
var finalFileName = fileName
if folderDirName.isEmpty == false {
let downloadsFolderName = folderDirName + "/"
if (fileName.starts(with: downloadsFolderName) == false) {
finalFileName = "\(downloadsFolderName)\(fileName)"
}
}
let destination: DownloadRequest.Destination = { _, _ in
let fileURL = FileHelper.shared.getFileURL(for: finalFileName) ?? URL(fileURLWithPath: finalFileName)
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
let progressQueue = DispatchQueue(label: "com.alamofire.progressQueue", qos: .utility)
let request = AF.download(urlString,
method: .get,
parameters: nil,
encoding: JSONEncoding.default,
headers: nil,
interceptor: nil,
requestModifier: nil,
to: destination)
.validate(statusCode: 200 ... 500)
.responseData(queue: .main) { response in
switch response.result {
case .success:
if let destinationURL = response.fileURL {
completion(.success(destinationURL))
} else {
let error = NSError(domain: "Network", code: 200) as Error
completion(.failure(error))
}
case .failure(let error):
// check if file exists before
if let destinationURL = response.fileURL {
if FileManager.default.fileExists(atPath: destinationURL.path) {
// File exists, so no need to override it. simply return the path.
completion(.success(destinationURL))
print()
} else {
completion(.failure(error))
}
} else {
completion(.failure(error))
}
}
}
request.resume()
}
}