无法对类型为"Auth"的非可选值使用可选链接 [英] Cannot use optional chaining on non-optional value of type 'Auth'

查看:139
本文介绍了无法对类型为"Auth"的非可选值使用可选链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

1-您应该像这样声明用户

1- You should declare the user like

var loggedInUser: FIRUser?

然后在viewDidLoad

loggedInUser = Auth.auth().currentUser

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

2- snapshat.value is of type Any so you need

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

3- Don't use NS ( use Data instead NSData ) stuff and avoid contentsOfURL

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

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

in loading remote urls as it blocks the main thread consider using SDWebImage

这篇关于无法对类型为"Auth"的非可选值使用可选链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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