下载图像,然后从 Firebase Swift 3 缓存它
Posted
技术标签:
【中文标题】下载图像,然后从 Firebase Swift 3 缓存它【英文标题】:Downloading Image, then Cache it from Firebase Swift 3 【发布时间】:2016-12-07 19:50:40 【问题描述】:我目前正在尝试设置用户个人资料图片。我让用户拍摄了一张上传到 Firebase 的图片,但我想下载该图片并将其缓存。我现在下载它时遇到问题,修复后我会担心缓存它。
// Uploading Images to Firebase
func uploadImageToFirebaseStorage(data: NSData )
let storageRef = FIRStorage.storage().reference(withPath: "myPics/profilePic.jpg")
let uploadMetaData = FIRStorageMetadata()
uploadMetaData.contentType = "image/jpeg"
let uploadTask = storageRef.put(data as Data, metadata: uploadMetaData) (metadata, error) in
if (error != nil)
print("I Received an error \(error?.localizedDescription)")
else
print("Upload Complete! Here is the MetaData \(metadata?.downloadURL())")
现在问题导航器有什么问题:
reference = self.storage
上有这个问题。提前谢谢!
//Download Image for User Profile Picture
func downloadImageUserFromFirebase()
let storage = FIRStorage.storage()
var reference: FIRStorageReference!
reference = self.storage.referenceForURL("gs:URL.appspot.com")
reference.downloadURL (url, error) in
let data = NSData(contentsOf: url!)
let image = UIImage(data: data! as Data)
self.profileImageView.image = image
【问题讨论】:
【参考方案1】:Storage 没有声明为类的属性,它是在该方法中声明的。此外,即使它被声明为类的属性,在 swift 中你不需要再将 self 放在类属性之前,除非你在闭包中。
要么做:
func downloadImageUserFromFirebase()
let storage = FIRStorage.storage()
var reference: FIRStorageReference!
//all I did here was remove self before storage
reference = storage.referenceForURL("gs:URL.appspot.com")
reference.downloadURL (url, error) in
let data = NSData(contentsOf: url!)
let image = UIImage(data: data! as Data)
self.profileImageView.image = image
或者,理想情况下,重构代码:
class ProfileViewController: UIViewController
//here we are initializing it as a property of the class
let storage = FIRStorage.storage()
func downloadImageUserFromFirebase()
var reference: FIRStorageReference = storage.referenceForURL("gs:URL.appspot.com")
reference.downloadURL (url, error) in
//using a guard statement to unwrap the url and check for error
guard let imageURL = url, error == nil
//handle error here if returned url is bad or there is error
return
guard let data = NSData(contentsOf: imageURL) else
//same thing here, handle failed data download
return
let image = UIImage(data: data)
self.profileImageView.image = image
【讨论】:
【参考方案2】:reference.downloadurl 将识别当前用户的图片,或者我们应该将 profileimageurl 保存在数据库中
【讨论】:
以上是关于下载图像,然后从 Firebase Swift 3 缓存它的主要内容,如果未能解决你的问题,请参考以下文章
Swift 3:tableView 复制从 Firebase 加载的图像
可以从 Swift 中的 firebase 在浏览器中看到的图像的 URL