从网络下载文件到App

从网络下载文件到App

========================

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
func downloadModels(_ path: [String], modelUrl: String) {
DispatchQueue.global().async {
for str in path {
let urlString = modelUrl + str
let encodeURLStr = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
log(encodeURLStr)
let url = URL.init(string: encodeURLStr)
log(url)
let request = URLRequest(url: url!)
let downloadTask = URLSession.shared.downloadTask(with: request,
completionHandler: { (location: URL?, _: URLResponse?, _: Error?)
-> Void in
// let theUrl = NSHomeDirectory() + "/Documents/ThreeDModels" + str
// let endRang = theUrl.range(of: "/" + theUrl.lastPathComponent)
// let thePath = String(theUrl[..<endRang!.lowerBound])
let name = str.lastPathComponent.replacingOccurrences(of: ("." + str.pathExtension), with: "")
let fileManager = FileManager.default
let urls: [URL] = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
let documentURL = urls.first!
let endRang = str.range(of: "/" + str.lastPathComponent)
let documentName = String(str[..<endRang!.lowerBound])
let url = documentURL.appendingPathComponent("threeDModels" + documentName, isDirectory: true)
var isDirectory: ObjCBool = ObjCBool(false)
let isExist = fileManager.fileExists(atPath: url.path, isDirectory: &isDirectory)
if !isExist {
do {
try fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
} catch {
log(error)
}
}
let filePath = url.path + "/" + name + "." + str.pathExtension
do {
if fileManager.fileExists(atPath: filePath ) {
try fileManager.removeItem(atPath: filePath)
}
try fileManager.moveItem(atPath: location!.path, toPath: filePath)
} catch {
log(error)
}
})
downloadTask.resume()
}
}
}