从Swift中的URL下载并保存文件
我正试图从Swift中的URL下载并保存文件,swift,coreml,urlsession,mlmodel,Swift,Coreml,Urlsession,Mlmodel,我正试图 从服务器下载文件(MLModel) 将该文件保存到设备 重新启动应用程序 使用文件保存到的URL(路径)访问下载的文件。。因此,我不必每次应用程序启动时都重新下载它 让download=URLSession.shared.downloadTask(带:url){(urlOrNil,response,error)在 如果let error=error{ 打印(“❌ \(#函数)\(错误)”中有错误 完成(无) 返回 } //保存mlModel的位置 guard let fileURL
- 从服务器下载文件(MLModel)
- 将该文件保存到设备
- 重新启动应用程序
- 使用文件保存到的URL(路径)访问下载的文件。。因此,我不必每次应用程序启动时都重新下载它
如果let error=error{
打印(“❌ \(#函数)\(错误)”中有错误
完成(无)
返回
}
//保存mlModel的位置
guard let fileURL=urlOrNil else{print(这就是答案
在downloadTask函数中,我打印了compiledUrl.lastPathComponent并保存了它。然后,当我重新运行应用程序时,我运行了以下代码来查找文件的URL
我看到许多文章看起来有些相似,但经过多次尝试和迭代后,答案对我来说并不适用。我可能只是不够聪明/经验不足,无法弥补不同的变量。如果我应该这样做,我很抱歉。
if let error = error {
print("❌ There was an error in \(#function) \(error)")
completion(nil)
return
}
// the location the mlModel is saved at
guard let fileURL = urlOrNil else {print("This was the answer.
inside of the downloadTask function, I printed the compiledUrl.lastPathComponent and saved it. Then, when I re-ran the app I ran this code to find the URL of the file.
// saved compiledUrl.lastPathComponent
let filename = "CFNetworkDownload_B9QvT1.mlmodelc"
let fileManager = FileManager.default
let appSupportDirectory = try! fileManager.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let permanentUrl = appSupportDirectory.appendingPathComponent(filename)
let model = try? MLModel(contentsOf: permanentUrl)
print(model)