Firebase使用Firebase数据库从URL保存中检索图像

时间:2016-06-07 17:34:46

标签: swift image firebase firebase-realtime-database firebase-storage

我已将图片保存到Firebase存储空间,并将imageURL保存到Firebase数据库,但是如何通过保存在firebase数据库中的URL恢复图像?这是我如何保存它

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
    userPhoto.image = image
    dismissViewControllerAnimated(true, completion: nil)
    var data = NSData()
    data = UIImageJPEGRepresentation(userPhoto.image!, 0.8)!
    // set upload path
    let filePath = "\(FIRAuth.auth()!.currentUser!.uid)/\("userPhoto")"
    let metaData = FIRStorageMetadata()
    metaData.contentType = "image/jpg"
    self.storageRef.child(filePath).putData(data, metadata: metaData){(metaData,error) in
        if let error = error {
            print(error.localizedDescription)
            return
        } else {
            // store downloadURL
            let downloadURL = metaData!.downloadURL()!.absoluteString
            // store downloadURL at database
            self.databaseRef.child("users").child(FIRAuth.auth()!.currentUser!.uid).updateChildValues(["userPhoto": downloadURL])
        }
    }
}

1 个答案:

答案 0 :(得分:2)

以下是一种方法:下载数据,然后为其创建UIImage

self.storage.referenceForURL(url).dataWithMaxSize(25 * 1024 * 1024, completion: { (data, error) -> Void in
    let image = UIImage(data: data!)
    chatMessage.image = image!
    self.messages.append(chatMessage)
    self.tableView.reloadData()
    self.scrollToBottom()
})

此代码来自Zero To App talk at Google I/O。完整代码可在this gist

中找到