从网络下载文件到App


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

文章作者: 张赛东
文章链接: https://zsd.name
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 张赛东 !
评论
  目录