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
}
})
}
}
}
}
}
}
2
Answers
Thanks to people who tried to help.
I solved it like this: