'How to view PDF from Firebase Storage - SwiftUI PDFVIEW

I am having some issues trying to display a PDF which is stored in Firebase Storage in my SwiftUI app.

I have successfully done the following;

  • Uploaded a PDF file to Firebase Storage
  • Get the URL from the directory path
  • Create a PDFView and pass the URL

Currently the PDFKITVIEW appears but with nothing to show, and no errors. What am I missing ?

Show PDFKITVIEW

.sheet(isPresented: $isShowingDoc) {
    PDFKitView(path: model.object.docURL) // Path to firebase storage is correct 
}

PDFKITVIEW

import SwiftUI
import PDFKit

struct PDFKitView : UIViewRepresentable {
    
    private var url: URL?
    
    init(path: String) {
        
        // Get url from path
        let dm = DataManager()
        url = dm.urlForDocPath(path: path)
    }
    
    func makeUIView(context: Context) -> UIView {
        let pdfView = PDFView()

        if let url = url {
            pdfView.document = PDFDocument(url: url)
        }
        
        return pdfView
    }
    
    func updateUIView(_ uiView: UIView, context: Context) {
        // Empty
    }
    
}

DataManager

func getURLFromFirestore(path: String, success:@escaping (_ docURL:URL)->(),failure:@escaping (_ error:Error)->()){
    
    let storage = Storage.storage().reference(withPath: path)
     storage.downloadURL { (url, error) in
         if let _error = error{
             print(_error)
             failure(_error)
         } else {
             if let docURL = url {
                 success(docURL)
             }
         }
     }
}

func urlForDocPath(path: String) -> URL? {
    var url: URL?
    
    getURLFromFirestore(path: path,  success: { (docURL) in
        url = docURL
    }) { (error) in
        print(error)
    }
    
    return url
}


Solution 1:[1]

I cannot post this as a comment since I haven't got enough reputation to do so but seems like the problem can be in your urlForDocPath function, which tries to do an async operation but returning synchronously.

Could you check if url is not nil on the PDFKitView? Because if it is, it will prove my point.

Didn't tried yet in Xcode but needs to be something like following:

func urlForDocPath(path: String, success: @escaping (_ docURL:URL?)->(), failure: @escaping (_ error:Error)->()) {
    var url: URL?

    getURLFromFirestore(path: path,  success: { (docURL) in
        success(docURL)
    }) { (error) in
        failure(error)
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Burak Akka?