i can't upload files to firebase with Swift

I have uploaded the photos on the user's phone to firebase with UIImagePickerController, but using UIdocumentPickerController, I load pdf and similar formats, but it loads an empty file and when I try to download the files I have uploaded, it downloads an empty file- I am new to Swift, can anyone help?

import UIKit
import Firebase
import MobileCoreServices
class DocViewController: UIViewController & UIDocumentPickerDelegate & UINavigationControllerDelegate{
@IBOutlet weak var docImage: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    
    // Do any additional setup after loading the view.
    let hideKeyboardGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
    view.addGestureRecognizer(hideKeyboardGesture)
    docImage.isUserInteractionEnabled = true
    let docGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(selectDocument))
    docImage.addGestureRecognizer(docGestureRecognizer)
}
@objc func hideKeyboard(){
    view.endEditing(true)
}
@objc func selectDocument(){
    let documentPicker = UIDocumentPickerViewController(documentTypes: [String(kUTTypePDF)], in: .open)
    documentPicker.delegate = self
    documentPicker.modalPresentationStyle = .fullScreen
    documentPicker.allowsMultipleSelection = false
    documentPicker.directoryURL = .documentsDirectory
    present(documentPicker, animated: true, completion: nil)
}
func alertFunc(titleInput:String, messageInput: String){
    let alert = UIAlertController(title: titleInput, message: messageInput, preferredStyle: UIAlertController.Style.alert)
    let okButton = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)
    alert.addAction(okButton)
    self.present(alert, animated: true, completion: nil)
}

@IBAction func uploadClicked(_ sender: Any) {
    let storage = Storage.storage()
    let storageReference = storage.reference()
    let newData = Data()
    let newUuid = UUID().uuidString
    let mediaFolder = storageReference.child("Documents")
    let newDocumentReference = mediaFolder.child("\(newUuid).pdf")
    newDocumentReference.putData(newData, metadata: nil) { metadata, error in
     if error != nil {
     self.alertFunc(titleInput: "Error", messageInput: error?.localizedDescription ?? "Error!!!")
     } else{
     newDocumentReference.downloadURL { url, error in
     if error == nil{
     let documentUrl = url?.absoluteString
     let documentFirestore = Firestore.firestore()
     var documentFirestoreReference : DocumentReference? = nil
     let firestorePost = ["imageUrl": documentUrl!, "PostedBy": Auth.auth().currentUser!.email!, "Date": FieldValue.serverTimestamp()] as [String : Any]
     documentFirestoreReference = documentFirestore.collection("Documents").addDocument(data: firestorePost, completion: { error in
     if error != nil {
     self.alertFunc(titleInput: "Error!!!", messageInput: error?.localizedDescription ?? "Error!!!")
     } else {
     self.tabBarController?.selectedIndex = 0
     }
     })
     }
     }
     
     }
     }
    
}

    
}

Upvotes: 3

Views: 337

Answers (2)

Thanks to people who tried to help.
I solved it like this:

import UIKit
import Firebase
import MobileCoreServices

class DocViewController: UIViewController & UIDocumentPickerDelegate & UINavigationControllerDelegate{
    @IBOutlet weak var docImage: UIImageView!
    var docUrl : URL? = nil
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        let hideKeyboardGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
        view.addGestureRecognizer(hideKeyboardGesture)
        docImage.isUserInteractionEnabled = true
        let docGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(selectDocument))
        docImage.addGestureRecognizer(docGestureRecognizer)
        
        
    }
   
    @objc func hideKeyboard(){
        view.endEditing(true)
    }
    @objc func selectDocument(){
        let documentPicker = UIDocumentPickerViewController(documentTypes: [String(kUTTypeItem)], in: .open)
        documentPicker.delegate = self
        documentPicker.modalPresentationStyle = .fullScreen
        documentPicker.allowsMultipleSelection = false
        present(documentPicker, animated: true, completion: nil)
    }
    
    func alertFunc(titleInput:String, messageInput: String){
        let alert = UIAlertController(title: titleInput, message: messageInput, preferredStyle: UIAlertController.Style.alert)
        let okButton = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)
        alert.addAction(okButton)
        self.present(alert, animated: true, completion: nil)
    }
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        docUrl = urls.first
        docImage.image = UIImage(systemName: "checkmark.icloud.fill")
        self.dismiss(animated: true, completion: nil)
    }
    
    @IBAction func uploadClicked(_ sender: Any) {
        docUrl!.startAccessingSecurityScopedResource() //this is important for not getting permission error 
        let data = try! Data(contentsOf: docUrl!)
        docUrl!.stopAccessingSecurityScopedResource()
        let storage = Storage.storage()
        let storageReference = storage.reference()
        let newUuid = UUID().uuidString
        let documentFolder = storageReference.child("Documents")
        let fileExtension = docUrl!.pathExtension
        let fileReference = documentFolder.child("\(newUuid).\(fileExtension)")
        fileReference.putData(data) { metadata, error in
            if error != nil {
                self.alertFunc(titleInput: "Error!!!", messageInput: error?.localizedDescription ?? "Error")
            } else {
                fileReference.downloadURL { url, error in
                    if error == nil {
                        let documentUrl = url?.absoluteString
                        let documentFirestore = Firestore.firestore()
                        var documentFirestoreReference : DocumentReference? = nil
                        let firestorePost = ["imageUrl": documentUrl!, "PostedBy": Auth.auth().currentUser!.email!, "Date": FieldValue.serverTimestamp()] as [String : Any]
                        documentFirestoreReference = documentFirestore.collection("Posts").addDocument(data: firestorePost, completion: { error in
                            if error != nil {
                                self.alertFunc(titleInput: "Error2!!!", messageInput: error?.localizedDescription ?? "Error2!!!")
                            } else {
                                self.tabBarController?.selectedIndex = 0
                            }
                        })
                    }
                }
            }
        }
        }
        }

Upvotes: 0

ali.ios
ali.ios

Reputation: 51

    // - Use below to save a file from your local bundle
    guard let localFileURL = Bundle.main.url(forResource: "YourFileName", withExtension: ".pdf") else {
        return
    }
    
    //  - Use below to save an image from your image library
    let imageData = image.pngData() or image.jpegData()
    
    // - Then save it as data rather than saving an empty data to your Firebase storage
    
    do {
        let data = try? Data(contentsOf: localFileURL)
    } catch (let error) {
        print("Error in \(#function) : \(error.localizedDescription) \n---\n \(error)")
    }

Upvotes: 1

Related Questions