无法转换类型' nsnull'到' nsstring'

时间:2016-02-03 20:14:24

标签: ios firebase

当我开始模拟它崩溃时,我试图从firebase检索图像,我得到了这个消息" 无法转换类型的值' NSNull' (0x10eaf2378)到' NSString' (0x10eee2b20)。" 这是我的代码

类ViewController:UIViewController {

@IBOutlet weak var gameName: UILabel!
@IBOutlet weak var videoImage: UIImageView!
@IBOutlet weak var uploadImage: UIButton!


var ref = Firebase(url:"https://xxx.firebaseio.com/images/")
var imageRef = Firebase(url:"https://xxx.firebaseio.com/images/image/string")
var base64String: NSString!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


    imageRef.observeEventType(.Value, withBlock: { (snapshot) -> Void in

        self.base64String = snapshot.value as? String
        let decodeData = NSData(base64EncodedString: snapshot.value as! String, options: NSDataBase64DecodingOptions())
        let decodeImage = UIImage(data: decodeData!)
        self.videoImage.image = decodeImage
        print(self.base64String)
        }) { (error) -> Void in
            print(error.description)
    }

}

1 个答案:

答案 0 :(得分:0)

imageRef.observeEventType(.Value, withBlock: { (snapshot) -> Void in

        guard let unwrappedSnapShot = snapshot.value as? String ,
              let decodeData        = NSData(base64EncodedString: unwrappedSnapShot, options: NSDataBase64DecodingOptions())
              else {  /*handle snapshot or decodData was nil*/ return }

         let decodeImage = UIImage(data: decodeData)
         self.videoImage.image = decodeImage
         print(base64String)      
}) { (error) -> Void in
        print(error.description)
}

删除了IUO的使用,你也不应该使用它们 你应该把一个捕获列表放在那里以避免保留周期