我正在我的应用程序上实现 Google 登录,我需要访问用户 ID 和名字/姓氏。存储该数据的变量位于 App Delegate 中。我在互联网上来回搜索,寻找如何在 Swift 3 中执行此操作,但一无所获。
这是 App Delegate(至少是重要的部分):
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {
var window: UIWindow?
var databaseRef: FIRDatabaseReference!
var userID = String()
var givenName = String()
var familyName = String()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Use Firebase library to configure APIs
FIRApp.configure()
GIDSignIn.sharedInstance().clientID = FIRApp.defaultApp()?.options.clientID
GIDSignIn.sharedInstance().delegate = self
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return GIDSignIn.sharedInstance().handle(url,
sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String,
annotation: options[UIApplicationOpenURLOptionsKey.annotation])
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let error = error {
print(error.localizedDescription)
return
}
print("User signed into Google")
let authentication = user.authentication
let credential = FIRGoogleAuthProvider.credential(withIDToken: (authentication?.idToken)!,
accessToken: (authentication?.accessToken)!)
FIRAuth.auth()?.signIn(with: credential) { (user, error) in
print("User Signed Into Firebase")
self.databaseRef = FIRDatabase.database().reference()
self.databaseRef.child("user_profiles").child(user!.uid).observeSingleEvent(of: .value, with: { (snapshot) in
let snapshot = snapshot.value as? NSDictionary
if(snapshot == nil)
{
self.databaseRef.child("user_profiles").child(user!.uid).child("name").setValue(user?.displayName)
self.databaseRef.child("user_profiles").child(user!.uid).child("email").setValue(user?.email)
}
})
}
userID = user.userID
givenName = user.profile.givenName
familyName = user.profile.familyName
continueToWallet()
}
在 View Controller 中,我正在调用 App delegate 并尝试接收数据,但它给我一个错误提示,“实例成员‘User ID’不能用于类型‘AppDelegate’”
class addToWalletController: UIViewController {
var ID = String()
let delegate = UIApplication.shared.delegate as! AppDelegate
let user = AppDelegate.userID
let firstName = AppDelegate.givenName
let lastName = AppDelegate.familyName
override func viewDidLoad() {
super.viewDidLoad()
}
}
我还尝试在 =AppDelegate.userID 中将 AppDelegate 与委托(delegate)切换,但它给了我同样的错误。怎么回事?
最佳答案
错误消息告诉您属性初始值设定项在“self”可用之前运行
。
也许你应该在 viewDidLoad
中初始化它
let delegate = UIApplication.shared.delegate as! AppDelegate
var user: String?
var firstName: String?
var lastName: String?
override func viewDidLoad() {
super.viewDidLoad()
user = delegate.userID
firstName = delegate.givenName
lastName = delegate.familyName
}
关于ios - 在 View Controller 中从 App Delegate 访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42522499/