ios - 从 Firebase JSON 获取图像

标签 ios swift firebase firebase-realtime-database

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

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

每次我对其进行编码时,它都会说试图解开一个 nil 值,这意味着我认为它找不到 URL 指向的图像。

提前致谢。这是我正在使用的获取代码:

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 检索图像即可。

常规设置

var storageRootRef: FIRStorageReference!
var databaseRootRef: FIRDatabaseReference!

override func viewDidLoad()
{
    super.viewDidLoad()

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

图像保存

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

Swift 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 进行检索,如下所示。

Swift 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: String = NSUUID().UUIDString + ".png" 或者你可以按照我的做法,即 var imageName: String = userUID + ".png"

  2. 上传之前,建议先压缩图片,以便更快地查询和检索。

关于ios - 从 Firebase JSON 获取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39597844/

相关文章:

iOS swift 如何将 imageview 准确地放置在 uiview 中

ios - 使用应用内购买或第三方支付网关

javascript - Firestore没有执行操作的权限

image - 我可以将图像作为文件而不是数据存储在 Firebase 上吗 :url?

ios - 从 UITapGestureRecognizer 中排除 subview

ios - 如何删除 NSMutableArray 中的重复字段,其中包括 Swift 3 中的 NSDictionary

ios ScrollView 的自动布局架构技巧

ios - CMMotionActivityManager 不适用于 iphone 5 ios 10.3.3

swift - 如何找出元组的哪个变量在 willSet/didSet 被更新了?

android - Firebase Android - startAt() 和 endAt() 无法正常工作?