【发布时间】:2020-11-06 11:22:27
【问题描述】:
我刚刚创建了一个应用程序,它只是从 url 下载 pdf 文件,将其保存到 cachesDirectory,然后使用 SwiftUI 在 pdfView 中显示它,请参阅我在 body 属性中的 cmets 以检查我做错了什么
struct ContentView: View {
@State var documentURL: URL?
@State var ispresented: Bool = false
func downloadFile(completion: @escaping (URL)->Void) {
guard let url = URL(string: "https://www.tutorialspoint.com/swift/swift_tutorial.pdf") else { return }
let task = URLSession.shared.downloadTask(with: url) { (localURL, response, error) in
if error == nil {
let docsPath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
let destinationPath = docsPath.appendingPathComponent(url.lastPathComponent)
try? FileManager.default.removeItem(at: destinationPath)
do {
try FileManager.default.copyItem(at: localURL!, to: destinationPath)
DispatchQueue.main.async { completion(destinationPath) }
} catch {
print("Error copying:\(error)")
}
}
}
task.resume()
}
var body: some View {
VStack {
Button(action: {
downloadFile { localUrl in
print("Closure url:\(localUrl)")
// here i am getting valid localUrl means i can see and open the downloaded file in finder when i follow the url in HardDisk
self.documentUrl = localUrl
UserDefaults.standard.set(localUrl, forKey: "url")
}
}, label: {
Text("Start Downloading")
})
Button("Open PDFView") {
ispresented.toggle()
}
}
.sheet(isPresented: $ispresented, content: {
PDFKitRepresentableView(url: documentURL!)
// here i am getting error that documentURL is nil
})
}
那么,我在这里做错了什么?提前致谢。
【问题讨论】: