This repository has been archived by the owner on Mar 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAssetManager.swift
155 lines (116 loc) · 5.86 KB
/
AssetManager.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
//
// AssetManager.swift
// Bomberman
//
// Created by Wolfgang Schreurs on 08/05/16.
//
//
import Foundation
import Zip
protocol AssetManagerDelegate: class {
func assetManagerLoadAssetsSuccess(_ assetManager: AssetManager)
func assetManagerLoadAssetsFailure(_ assetManager: AssetManager, error: Error)
func assetManagerLoadAssetsProgress(_ assetManager: AssetManager, progress: Float)
}
// TODO: The AssetManager should store / load Etags internally. The Etag methods should be private
// to simplify the interface.
class AssetManager: NSObject {
fileprivate let etagKey = "etag"
fileprivate let fileManager = FileManager.default
fileprivate let userDefaults = UserDefaults.standard
fileprivate var buffer = NSMutableData()
fileprivate var session: Foundation.URLSession?
fileprivate var dataTask: URLSessionDataTask?
fileprivate var expectedContentLength = 0
fileprivate let filename = "assets.zip"
weak var delegate: AssetManagerDelegate?
// MARK: - Public
func etagForRemoteAssetsArchive(_ assetsSourceURL: URL) throws -> String? {
var etag: String?
let request = NSMutableURLRequest(url: assetsSourceURL)
request.httpMethod = "HEAD"
let sessionConfiguration = URLSessionConfiguration.default
sessionConfiguration.timeoutIntervalForResource = 5
let session = Foundation.URLSession(configuration: sessionConfiguration)
let (data, response, error) = session.synchronousDataTaskWithRequest(request as URLRequest)
print("response: \(String(describing: response)), data: \(String(describing: data)), error: \(String(describing: error))")
if let httpResponse = response as? HTTPURLResponse {
etag = httpResponse.allHeaderFields["Etag"] as? String
}
return etag
}
func etagForLocalAssetsArchive() -> String? {
var etag: String?
if let destinationDirectoryPath = fileManager.bundleSupportDirectoryPath() {
let assetsDestinationPath = destinationDirectoryPath.stringByAppendingPathComponent(self.filename)
if fileManager.fileExists(atPath: assetsDestinationPath) {
etag = userDefaults.value(forKey: etagKey) as? String
}
}
return etag
}
func storeEtagForLocalAssetsArchive(_ etag: String?) {
userDefaults.setValue(etag, forKey: etagKey)
userDefaults.synchronize()
}
func loadAssets(_ assetsSourceURL: URL) {
prepareForAssetsLoading()
let identifier = "net.wolftrail.Bomberman.assetLoader"
let configuration = URLSessionConfiguration.background(withIdentifier: identifier)
let delegateQueue = OperationQueue.main
let session = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: delegateQueue)
let dataTask = session.dataTask(with: assetsSourceURL)
dataTask.resume()
}
// MARK: - Private
fileprivate func unzipAssets(fromData data: Data, assetsDestinationURL: URL) throws {
// Copy the zip file to the destnation path
try data.write(to: assetsDestinationURL, options: .atomicWrite)
let destinationDirectoryUrl = (assetsDestinationURL.deletingLastPathComponent())
// Finally we can unzip the archive in the destination directory.
try Zip.unzipFile(assetsDestinationURL, destination: destinationDirectoryUrl,
overwrite: true,
password: nil,
progress: { (progress) in
print("progress: \(progress)")
})
}
fileprivate func prepareForAssetsLoading() {
self.buffer = NSMutableData()
self.expectedContentLength = 0
}
}
// MARK: - NSURLSessionDataDelegate
extension AssetManager : URLSessionDataDelegate {
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
print("response received: \(response)")
var responseDisposition = Foundation.URLSession.ResponseDisposition.cancel
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
self.expectedContentLength = Int(response.expectedContentLength)
responseDisposition = Foundation.URLSession.ResponseDisposition.allow
}
completionHandler(responseDisposition)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
self.buffer.append(data)
let progress = Float(buffer.length) / Float(expectedContentLength)
self.delegate?.assetManagerLoadAssetsProgress(self, progress: progress)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
print("completed task: \(task), error: \(String(describing: error))")
if error != nil {
self.delegate?.assetManagerLoadAssetsFailure(self, error: error!)
} else {
// Create the bundle support directory path if needed.
let destinationDirectoryPath = (fileManager.bundleSupportDirectoryPath())!
// Create the destination download URL for the assets zip file.
let assetsDestinationUrl = URL(fileURLWithPath: destinationDirectoryPath.stringByAppendingPathComponent(self.filename))
do {
try unzipAssets(fromData: self.buffer as Data, assetsDestinationURL: assetsDestinationUrl)
self.delegate?.assetManagerLoadAssetsSuccess(self)
} catch let error {
self.delegate?.assetManagerLoadAssetsFailure(self, error: error)
}
}
}
}