从Firebase JSON获取图像 [英] Getting images from Firebase JSON

查看:32
本文介绍了从Firebase JSON获取图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以从Firebase数据库中获取图像?我知道我可以使用存储,但是对于我的特殊情况,需要进行很多更改,如果可以将信息输入到JSON树中并以这种方式获取,它将容易得多.

I was wondering if it were possible to fetch an image from the Firebase Database? I know that I can use the storage but for my particular situation it needs to be altered a lot and would be a lot easier if I could enter in the information into the JSON tree and fetch it that way.

简而言之,我的问题是我可以使用Firebase存储部分中的URL并将其复制并粘贴到JSON树中的子项中,并像在数据库中使用其他任何数字或字符串一样检索它吗?

So in short, my question is can I use the URL from the storage section of Firebase and copy and paste that into a child in the JSON tree and retrieve it as I would any other number or string in the database?

每次我编写代码时,它都会尝试解开nil值,这意味着我没有找到URL指向的图像.

Every time I code it out it says trying to unwrap a nil value which means it is not finding the image that the URL is pointing to, I assume.

先谢谢了.这是我正在使用的提取代码:

Thanks in advance. Here is the Fetch code that I am using:

let newsimage1 = cell.viewWithTag(3) as! UIImageView
let fetch2 = BASE_URL.child("/AA News Feed 1/Image")
fetch2.observeEventType(.Value, withBlock: { snapshot in
    let base64EncodedString = snapshot.value
    let imageData = NSData(base64EncodedString: base64EncodedString as! String,
                options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
    let decodedImage = UIImage(data:imageData!)!
    newsimage1.image = decodedImage
}, withCancelBlock: { error in
    print(error.description)
})

推荐答案

建议的方法通常是从Firebase检索图像的方法.您只需将URL存储在您的 FirebaseDatabase 中,然后使用它从 FirebaseStorage 中检索图像.

The method you suggested is generally how you'd retrieve an image from Firebase. You simply store the URL in your FirebaseDatabase then use it to retrieve the image from FirebaseStorage.

常规设置

var storageRootRef: FIRStorageReference!
var databaseRootRef: FIRDatabaseReference!

override func viewDidLoad()
{
    super.viewDidLoad()

    storageRootRef = FIRStorage.storage().reference()
    databaseRootRef = FIRDatabase.database().reference()
}

图像保存

您首先需要将图像保存到 FirebaseStorage ,然后检索其位置的 downloadURL ,然后您才能继续将此信息写入您的 FirebaseDatabase如下所示

You first need to save the image to FirebaseStorage then retrieve the downloadURL of its location, then only can you go ahead and write this info into your FirebaseDatabase as shown below

快捷键2

func createUserToDatabase()
{
    storageRootRef = storageRootRef.child("ProfileImages").child(self.currentUser.uid + ".png")

    if let imageData = UIImagePNGRepresentation(currentUser.profileImage)
    {
        storageRootRef.putData(imageData, metadata: nil, completion: { (metadata: FIRStorageMetadata?, error: NSError?) in

            if let storageError = error
            {
                print("Firebase Upload Error")
                print(storageError.localizedDescription)
                return
            }
            else if let storageMetadata = metadata
            {
                if let imageURL = storageMetadata.downloadURL()
                {
                    self.currentUser.profileImageURL = imageURL.absoluteString
                    // TODO: Now you may write to your Firebase Database since you already have the imageURL stored.
                }
            }
        })
    }
}

Swift 3

func createUserToDatabase()
{
    storageRootRef = storageRootRef.child("ProfileImages").child(self.currentUser.uid + ".png")

    if let imageData = UIImagePNGRepresentation(currentUser.profileImage)
    {
        storageRootRef.put(imageData, metadata: nil, completion: { (metadata: FIRStorageMetadata?, error: Error?) in

            if let storageError = error
            {
                print("Firebase Upload Error")
                print(storageError.localizedDescription)
                return
            }
            else if let storageMetadata = metadata
            {
                if let imageURL = storageMetadata.downloadURL()
                {
                    self.currentUser.profileImageURL = imageURL.absoluteString
                    // TODO: Now you may write to your Firebase Database since you already have the imageURL stored.
                }
            }
        })
    }
}

图像检索

只需在您的 FirebaseDatabase 中查询 imageURL ,然后启动 URLSession 进行检索,如下所示.

Simply query into your FirebaseDatabase for the imageURL, then initiate a URLSession for its retrieval as shown below.

快捷键2

func retrieveUserData()
{
    databaseRootRef!.child("path").observeSingleEventOfType(
    .Value) { (snapshot: FIRDataSnapshot) in

        if let firebaseValue = snapshot.value
        {
            self.currentUser.profileImageURL = firebaseValue["profileImageURL"] as! String
        }

        let imageURL: NSURL = NSURL(string: self.currentUser.profileImageURL)!

        NSURLSession.sharedSession().dataTaskWithURL(imageURL, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) in

            if let sessionError = error
            {
                print("Error Downloading Image")
                print(sessionError.localizedDescription)
            }
            else if let sessionData = data
            {
                dispatch_async(dispatch_get_main_queue(), {

                    self.currentUser.profileImage = UIImage(data: sessionData)!
                })
            }
        }).resume()
    }
}

Swift 3

func retrieveUserData()
{
    databaseRootRef!.child("path").observeSingleEvent(
    of: .value) { (snapshot: FIRDataSnapshot) in

        if let firebaseValue = snapshot.value as? [String:AnyObject]
        {
            self.currentUser.profileImageURL = firebaseValue["profileImageURL"] as! String
        }

        let imageURL: URL = URL(string: self.currentUser.profileImageURL)!

        URLSession.shared.dataTask(with: imageURL, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in

            if let sessionError = error
            {
                print("Error downloading image")
                print(sessionError.localizedDescription)
            }
            else if let sessionData = data
            {
                DispatchQueue.main.async(execute: {
                    self.currentUser.profileImage = UIImage(data: sessionData)!
                })
            }

        }).resume()
    }
}

编辑

  1. FirebaseStorage 不再允许您将文件直接添加到根目录中,因此建议创建目录而不是将图像存储在其中.出于独特的目的,图像名称的格式可以为<代码> var imageName:字符串= NSUUID().UUIDString +".png" ,或者您可以做我所做的 var imageName:String = userUID +".png" .

  1. FirebaseStorage no longer allows you to add files directly into the root so it's advisable to create directories instead to store your images in. For unique purposes, your image names can be of format var imageName: String = NSUUID().UUIDString + ".png" or you could do what I did which was var imageName: String = userUID + ".png".

在上传之前,建议先压缩图像以加快查询和检索的速度.

Before uploading, its advisable to compress your images first for faster queries and retrievals.

这篇关于从Firebase JSON获取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆