【问题标题】:How to upload a file to Firebase in an iOS app (Swift)如何在 iOS 应用 (Swift) 中将文件上传到 Firebase
【发布时间】:2021-11-20 13:20:28
【问题描述】:
【问题讨论】:
标签:
swift
xcode
firebase
google-cloud-storage
【解决方案1】:
您过去能够选择文件的答案工作正常,但没有在didFinishPickingMediaWithInfo 和didPickDocumentsAt 函数的范围之外提供对所选图像或文件的引用。
以下是保存文件/图像数据以便以后访问的方法。
// Image
if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
// The following 2 lines don't actually do anything: the selectedImageData dictionary
// ceases existing as soon as the functions ends
// selectedImageData["filename"] = fileUrl.lastPathComponent
// selectedImageData["data"] = pickedImage.pngData()?.base64EncodedString(options: .lineLength64Characters)
self.myData = pickedImage.pngData()
}
// File
do {
let fileData = try Data.init(contentsOf: file.absoluteURL)
// The following 2 lines don't actually do anything: the selectedFileData dictionary
// ceases existing as soon as the functions ends
// selectedFileData["filename"] = file.lastPathComponent
// selectedFileData["data"] = fileData.base64EncodedString(options: .lineLength64Characters)
self.myData = fileData
} catch {
// ...
}
然后,要将数据上传到 Firebase 存储,您可以使用以下函数:
import FirebaseStorage // At the beginning of the file
// Uploads the selected image/file data there is any.
func uploadSavedData() {
guard let data = myData else { return } // Checks whether there is actual data to upload.
let storageRef = Storage.storage().reference()
let fileRef = storageRef.child("userUID/files/documentName.png")
let uploadTask = fileRef.putData(data, metadata: nil) { (metadata, error) in
guard let metadata = metadata else { return } // Cancels task if there is any error
fileRef.downloadURL { (url, error) in {
guard let downloadURL = url else { return }
print(downloadURL) // Prints the URL to the newly uploaded data.
}
}
}
有关该主题的更多资源