【发布时间】:2018-07-22 17:50:50
【问题描述】:
在将 Alamofire 下载到我们的应用程序之前,我正在创建一个测试项目。现在,我面临一个奇怪的问题,也许我不明白 Alamofire 下载或 FileManager 的工作原理。
我只是从一个 URL 下载 3 个文件,并希望将它们存储在文件系统中。之后,我想将它们用作 WKWebView 中的本地数据(尚未实现)。
这是我的视图控制器:
import UIKit
class ViewController: UIViewController {
@IBAction func loadWebsite(_ sender: Any) {
NetworkService.shared.getFile(path: "webview.html", completion: {
NetworkService.shared.getFile(path: "css/style.css", completion: {
NetworkService.shared.getFile(path: "images/square.jpg", completion: {
self.fillInContent()
})
})
})
}
private func fillInContent() {
let documentURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileUrl = documentURL.appendingPathComponent("webview.html")
if FileManager.default.fileExists(atPath: fileUrl.absoluteString) {
print("True")
} else {
print("no webview")
}
}
}
我知道加载资源的代码在完成块中启动新请求时写得不是很好,但它只是一个测试项目。
这是我的 NetworkService 单例:
import UIKit
import Alamofire
class NetworkService {
static let shared = NetworkService()
// Thread-safe
private init() {}
func getFile(path: String, completion: @escaping() -> Void) {
let destination: DownloadRequest.DownloadFileDestination = {_, _ in
let documentURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentURL.appendingPathComponent(path)
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download("https://myurl.com/" + path, to: destination)
.responseData { response in
if let error = response.result.error {
print("Error: \(error.localizedDescription)")
}
completion()
}
}
}
当我打印出 NetworkService 中的文件 URL 或 VC 中的 fillInContent() 时,它们是正确的。但是,fillInContent() 方法总是打印出“no webview”。所以文件不存在。我希望它会被其他完成块覆盖,但即使我在完成块中启动函数,fileExist() 也会返回 false。即使我删除了对 getFile() 的其他 2 个调用,我也不会在这里得到 fileExists 的真实情况。
当前行为:我一直收到“无网络视图”。
预期行为:fillInContent() 方法输出“True”。
非常感谢任何帮助或指导!
编辑: 运行项目两次后,我也收到此错误消息:'错误:文件“文档”无法保存在文件夹“1E07C511-B5B3-4B5A-84E1- 8EF61F6B7340”,因为已经存在同名文件。'
【问题讨论】:
标签: ios swift alamofire nsfilemanager