swift - 不能对“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-您应该声明用户喜欢
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
推荐阅读
- cordova - Keycloak认证后返回cordova app
- react-admin - 是否可以禁用某些行的展开?
- sql - 如何使用“OVER(PARTITION BY ...)”来区分
- r - 如何一次导入多个 .csv 文件?错误:“视图(X.csv”)中出现意外符号
- ios - WKWebView 如何在显示键盘时禁用adjustedContentInset?
- android - RxJava Junit4 多重可观察测试
- java - 我怎样才能合并活跃的反应流?
- javascript - AWS.ApiGatewayManagementApi BadRequestException:无效的 connectionId
- spring-boot - 无法将 Spring Boot 应用程序用作另一个 Spring Boot 应用程序的依赖项
- gitlab - x509: 未知权威机构签署的证书 PANIC: 未能注册此运行器