首页 > 解决方案 > 将 PNG 图像从 Firestore 设置为 UIImage.image --- Swift

问题描述

我正在尝试将此 UIImageView 图像(profileImage)设置为我从 Firestore 下载的。我没有收到任何错误,它运行良好,但 profileImage 包含视图背景颜色,而不是从 Firestore 下载的图像。

在此处查看结果图像

storage = Storage.storage().reference(forURL: "gs://senlink-6d966.appspot.com")
profilePath = storage.child("users_profile/\(Auth.auth().currentUser!.uid).png")
profilePath?.downloadURL(completion: { (url, error) in
            if error != nil {
                print("\(error!)")
            } else {
                if let url = url {
                    DispatchQueue.main.async {
                        let data = UIImage(data: url.absoluteURL.dataRepresentation)
                        self.profileImg.image = data
                    }
                }
            }
        }) 

标签: iosswiftxcode

解决方案


downloadURL方法返回图像数据的 url,而不是实际的图像数据。要直接下载图像数据,您可以使用getData. 这是文档中的示例:

// Create a reference to the file you want to download
let islandRef = storageRef.child("images/island.jpg")

// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
islandRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
  if let error = error {
    // Uh-oh, an error occurred!
  } else {
    // Data for "images/island.jpg" is returned
    let image = UIImage(data: data!)
  }
}

这应该做你想要的:

storage = Storage.storage().reference(forURL: "gs://senlink-6d966.appspot.com")
profilePath = storage.child("users_profile/\(Auth.auth().currentUser!.uid).png")
profilePath?.getData(maxSize: 1 * 1024 * 1024) { data, error in
  if let error = error {
    // Uh-oh, an error occurred!
  } else {
    // Data for your image
    let image = UIImage(data: data!)
    DispatchQueue.main.async {
        self.profileImg.image = image
    }
  }
}

推荐阅读