Swift:Firebase 存储代码块未执行

Posted

技术标签:

【中文标题】Swift:Firebase 存储代码块未执行【英文标题】:Swift: Firebase Storage Code Block Not Executing 【发布时间】:2020-06-04 16:09:51 【问题描述】:

我有以下函数可以从 Firebase 存储数据库中提取图像。

由于某种原因,print(imageRef) 行运行良好,但 imageRef.getData() 代码块被完全跳过。它没有执行任何打印语句“错误更新...”或“获取图像”。

这可能是什么原因造成的?

    func updateCurrentUser() 

        var downloadedImages : [UIImage?] = []

        for i in 0...8 
            let storageRef = Storage.storage().reference()

            let imageRef = storageRef.child(self.currentUser.userid + "/img" + String(i) + ".jpg")
            print(imageRef)

            // Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
            imageRef.getData(maxSize: 1 * 1024 * 1024)  data, error in
                if let error = error 
                    print("error updating returning user: \(error.localizedDescription)")
                 else 
                    // Data for the image is returned
                    let image = UIImage(data: data!)
                    downloadedImages[i] = image
                    print("Got the image")
                
            
        

        self.currentUser.images = downloadedImages
    

【问题讨论】:

【参考方案1】:

Firebase 是异步的,firebase 数据仅在 firebase 函数之后的闭包内有效。简而言之,代码比互联网快,数据下载需要时间。

这是您的代码的缩写版本...注意 cmets

func updateCurrentUser() 
    var downloadedImages : [UIImage?] = []
    for i in 0...8 
        imageRef.getData(maxSize: 1 * 1024 * 1024)  data, error in
           //firebase data is ONLY valid here so append each image to an array
           self.currentUser.images.append(downloadedImage)
        
    

    //the following line will execute WAY before the images are downloaded
    //   so self.currentUser.images will always be empty
    self.currentUser.images = downloadedImages

您可能还想使用完成处理程序。查看我的回答this question 进一步阅读

【讨论】:

以上是关于Swift:Firebase 存储代码块未执行的主要内容,如果未能解决你的问题,请参考以下文章

Swift 3 从 Firebase 获取用户数据

Async / Await嵌套问题?代码块未执行

ViewDidLoad 未按正确顺序执行操作 - Firebase、Swift

iOS 转发地理编码块未执行

使用自动增量 Swift 3 在 Firebase 数据库中存储帖子(图像、标题)

将文件上传到 s3,然后将 URL 存储在 Firebase - Swift 2.2