简体   繁体   中英

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
     }
     })
     }
     }
     
     }
     }
    
}

    
}

When the user selects their photo the below function will be called which will get the image data and pass it on to an Photo upload function.

You can use the below function to upload an Photo up by UIImagePickerController to a Firebase Cloud storage.

I hope this little cheat sheet will be of some value to you. If you are interested to learn more about Firebase and Swift, please check the list of video courses below. And hopefully one of them will be what you were looking for.

    // - 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)")
    }

I tried with firebase's putfile and putdata methods but it didn't work

@IBAction func uploadClicked(_ sender: Any) {
        let storage = Storage.storage()
        let storageReference = storage.reference()
        let newUuid = UUID().uuidString
        guard let localFile = Bundle.main.url(forResource: "Documents" , withExtension: "\(newUuid).pdf") else { return }

        storageReference.putData(try! Data(contentsOf: localFile), metadata: nil) { metadata, error in
            if error != nil {
                self.alertFunc(titleInput: "Error", messageInput: error?.localizedDescription ?? "Error!!!")
            } else{
                storageReference.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
                            }
                        })
                    }
                }
                
                
            }
            
        }








    @IBAction func uploadClicked(_ sender: Any) {
        let storage = Storage.storage()
        let storageReference = storage.reference()
        let newUuid = UUID().uuidString
        guard let localFile = Bundle.main.url(forResource: "Documents" , withExtension: "\(newUuid).pdf") else { return }
        let docReference = storageReference.child("\(newUuid).pdf")
        let uploadTask = docReference.putFile(from: localFile) { metadata, error in
            if error != nil{
                self.alertFunc(titleInput: "Error!!!", messageInput:error?.localizedDescription ?? "Error!!!")
            } else {
                docReference.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
                            }
                        })
                    }
                }
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM