[英]Cannot use optional chaining on non-optional value of type '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
将Auth.auth()?.currentUser
替换为Auth.auth().currentUser
。
auth()
返回一个非可选类型,所以你不能使用它的可选链接。
看看它的文档,它返回一个类型为Auth
而不是Auth?
的对象Auth?
.
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.