从网络下载文件到App
========================
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()
}
}
}