【问题标题】:How to upload a file to Firebase in an iOS app (Swift)如何在 iOS 应用 (Swift) 中将文件上传到 Firebase
【发布时间】:2021-11-20 13:20:28
【问题描述】:

我使用这个答案https://stackoverflow.com/a/64168754/16212254 作为参考,以允许用户选择一个文件,但现在我被困在如何将文件上传到 Firebase 上。 我是 Swift 新手,请不要介意我的愚蠢问题。

我尝试关注https://firebase.google.com/docs/firestore/quickstart#ioshttps://firebase.google.com/docs/storage/ios/upload-files,但由于我不知道附件的名称和路径,因此仍然无法弄清楚如何将文件发送到 Firebase。

【问题讨论】:

  • 可以查看this的文章

标签: swift xcode firebase google-cloud-storage


【解决方案1】:

您过去能够选择文件的答案工作正常,但没有在didFinishPickingMediaWithInfodidPickDocumentsAt 函数的范围之外提供对所选图像或文件的引用。

以下是保存文件/图像数据以便以后访问的方法。

  • 在您的 ViewController 中创建一个 Data? 类型的变量。

    var myData: Data?

  • 如果你正在处理一个图像,在didFinishPickingMediaWithInfo函数中,将所选图像的png数据保存在新创建的变量中(其范围不限于函数本身)。如果您要处理文件,请在 didPickDocumentAt 函数中执行基本相同的操作。

// 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.
        }
    }
}

有关该主题的更多资源

【讨论】:

    猜你喜欢
    • 2019-03-29
    • 2017-10-14
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多