簡體   English   中英

即使我給一個 url 變量一個值,我也得到一個 nil 值,所以我想知道我做錯了什么?

[英]I am getting a nil value even if i give a url variable a value, so i want to know what am i doing wrong?

我剛剛創建了一個應用程序,它只是從 url 下載 pdf 文件,將其保存到 cachesDirectory,然后使用 SwiftUI 將其顯示在 pdfView 中,請參閱我在 body 屬性中的評論以檢查我做錯了什么

    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

                    
                })
     }

那么,我在這里做錯了什么? 提前致謝。

這似乎是由 downloadFile 進行異步調用引起的問題,我不確定為什么它不起作用,但我設法讓它與下面的解決方案一起使用,我跳過了完成處理程序並在里面分配了文檔 URL 屬性URLSession 關閉代替

所以do子句改為

do {
    try FileManager.default.copyItem(at: localURL!, to: destinationPath)
    documentUrl = destinationPath
}

為了使 UI 更清晰,我在第二個按鈕中添加了一個disabled運算符,因此在下載文件之前您無法單擊它

Button("Open PDFView") {
    ispresented.toggle()
}.disabled(documentUrl == nil)

請注意,如果您想在那里做其他事情,當然可以保留閉包,但此解決方案不需要

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM