从Firebase数据库检索图像

时间:2019-07-22 18:54:05

标签: swift firebase firebase-realtime-database null

当尝试从Firebase访问URL时,它在数据库调用之外变为nil。我想从firebase调用一个变量,然后在整个方法中都可以使用它,所以必须有一个简单的解决方案来解决我遗漏的问题?

我尝试了从数据库中调用的多种方法,但是它们似乎都没有分配全局值,甚至我可以在整个方法中使用的值

import UIKit
import FirebaseDatabase
import Firebase
import FirebaseUI

class mapViewController: UIViewController, UIScrollViewDelegate {

    var imageViewBackground: UIImageView!
    var ref2:DatabaseReference?
    var mapURL: String?
    override func viewDidLoad() {

        super.viewDidLoad()
        let width = UIScreen.main.bounds.size.width
        let height = UIScreen.main.bounds.size.height

        imageViewBackground = UIImageView(frame: CGRect(x:0, y:0, width:width, height:height))
        var image: UIImage?
        ref2 = Database.database().reference()

        ref2?.child("map").observe(.childAdded) { (snapshot: DataSnapshot) in

            if let dict = snapshot.value as? [String: Any]{
                self.mapURL = dict["picurl"] as! String
            }
        }
        let urlString = self.mapURL!
        let url = NSURL(string: urlString)! as URL
        if let imageData: NSData = NSData(contentsOf: url) {
            image = UIImage(data: imageData as Data)
        }

        imageViewBackground.image = image
        imageViewBackground.contentMode = UIView.ContentMode.scaleAspectFit
        imageViewBackground.contentMode = UIView.ContentMode.center
        // you can change the content mode:
        imageViewBackground.contentMode = UIView.ContentMode.scaleAspectFill

让urlString = self.mapURL!返回nil异常

0 个答案:

没有答案