无法对类型为“ Auth”的非可选值使用可选链接

时间:2019-04-22 19:38:47

标签: swift firebase firebase-realtime-database optional

var loggedInUser: User?

let storageRef = Storage.storage().reference()
let databaseRef = Database.database().reference()


// structure definition goes here
override func viewDidLoad() {
    super.viewDidLoad()

    self.loggedInUser = Auth.auth()?.currentUser//Cannot use optional chaining on non-optional value of type 'Auth' 

    self.databaseRef.child("user_profiles").child(self.loggedInUser!.uid).observeSingleEventOfType(.Value) { (snapshot:DataSnapshot) in //'observeSingleEventOfType(_:withBlock:)' has been renamed to 'observeSingleEvent(of:with:)'

        self.name.text = snapshot.value!["name"] as? String//Type 'Any' has no subscript members
        self.handle.text = snapshot.value!["handle"] as? String//Type 'Any' has no subscript members

        //initially the user will not have an about data

        if(snapshot.value!["about"] !== nil)
        {
            self.about.text = snapshot.value!["about"] as? String
        }

        if(snapshot.value!["profile_pic"] !== nil)//Type 'Any' has no subscript members
        {
            let databaseProfilePic = snapshot.value!["profile_pic"]
                as! String//Type 'Any' has no subscript members

            let data = NSData(contentsOfURL: NSURL(string: databaseProfilePic)!)

            self.setProfilePicture(self.profilePicture,imageToSet:UIImage(data:data!)!)
        }

        //self.imageLoader.stopAnimating()
    }
    // Do any additional setup after loading the view.
}

var loggedInUser = AnyObject?()//this code was giving me an error 
//Cannot invoke initializer for type 'AnyObject?' with no arguments

然后我将其切换为:

var loggedInUser: User?// still giving me errors

2 个答案:

答案 0 :(得分:0)

Auth.auth()?.currentUser替换为Auth.auth().currentUser

auth()返回非可选类型,因此您不能对其使用可选链接。

看看它的documentation,它返回类型为Auth而不是Auth?的对象。

答案 1 :(得分:0)

1-您应该将用户声明为

var loggedInUser: FIRUser?

然后在viewDidLoad

中分配它
loggedInUser = Auth.auth().currentUser

2- snapshat.value的类型为Any,因此您需要

let value = snapshot.value as! [String:Any]  // you can do [String:String]  if all values are strings 
self.name.text = value["name"] as! String
self.handle.text = value["handle"] as! String

3-不要使用NS(请使用Data而不是NSData),并避免使用contentsOfURL

let data = NSData(contentsOfURL: NSURL(string: databaseProfilePic)!)

在阻止远程线程加载远程URL时,请考虑使用SDWebImage