簡體   English   中英

我想在 google 登錄方法中從 App 委托執行 segue

[英]i want to perform a segue from the App delegate in the google sign in method

我已經使用 firebase 實現了 Google 登錄,但遇到了問題。

如果 if 語句為真,我正在嘗試從 App 委托執行 segue。 if 語句有效,但每當我運行 perform segue 方法時,我都會收到帶有嵌入消息的信號錯誤或錯誤訪問錯誤:

viewController 沒有帶有標識符“Test”的 segue。 擴展名用於獲取電子郵件的子字符串,而頂部的 var 無關緊要。 我知道已經有人問過這個問題,但它對我不起作用,我認為這可能與 Google 登錄有關。 我的 segue 名稱是測試。 performSegue(withIdentifier: "Wegue", sender: self) 用於調用 google 登錄后的初始視圖控制器。

let userDefault  = UserDefaults()



func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
    if let error = error{
        print(error.localizedDescription)
        return


    }else{
        let userId = user.userID                  // For client-side use only!
        let idToken = user.authentication.idToken // Safe to send to the server
        let fullName = user.profile.name
        let givenName = user.profile.givenName
        let familyName = user.profile.familyName
        let email = user.profile.email
        let str = email



        if(str == "wafster1337@gmail.com"){
            self.window?.rootViewController?.performSegue(withIdentifier: "Test", sender: self)


        }
        else{
            print("woe")


        }


        guard let authentication = user.authentication else{return}
        let crendential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)
        Auth.auth().signInAndRetrieveData(with: crendential) {(result, error)in
        if error == nil {
           self.userDefault.set(true, forKey: "usersignedIn")
            self.userDefault.synchronize()
            self.window?.rootViewController?.performSegue(withIdentifier: "Wegue", sender: self)

        }else {

            print(error?.localizedDescription ?? "me")
            }
    }




    }


}



var window: UIWindow?




func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    FirebaseApp.configure()
    // Use Firebase library to configure APIs

    GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
    GIDSignIn.sharedInstance().delegate = self
    return true
}

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    return GIDSignIn.sharedInstance().handle(url,
                                             sourceApplication:options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
                                             annotation: [:])
}
func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

}
extension String {

var length: Int {
    return count
}

subscript (i: Int) -> String {
    return self[i ..< i + 1]
}

func substring(fromIndex: Int) -> String {
    return self[min(fromIndex, length) ..< length]
}

func substring(toIndex: Int) -> String {
    return self[0 ..< max(0, toIndex)]
}

subscript (r: Range<Int>) -> String {
    let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)),
                                        upper: min(length, max(0, r.upperBound))))
    let start = index(startIndex, offsetBy: range.lowerBound)
    let end = index(start, offsetBy: range.upperBound - range.lowerBound)
    return String(self[start ..< end])
}

}

您首先需要導入 google 和 firebase 庫。

import FirebaseAuth
import GoogleSignIn

登錄功能

public func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
    if (error == nil) {
        guard let authentication = user.authentication else { return }
        let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)
        Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
            if let error != nil {
                print("\(error)")
                return
            } else {
                // User is succesfully logged in so settting userDefaults (I wouldn't recommend doing it this way to check if user logged in!)
                UserDefaults.standard.set(true, forKey: "usersignedIn")
                UserDefaults.standard.synchronize()

                // Now perform the segue to the viewController you want. Make sure you set the identifier the same as in the storyboard
                let VC1 = (self.storyboard?.instantiateViewController(withIdentifier: "yourIdentifier"))!
                self.present(VC1, animated: true, completion: nil)
            }
        }
    } else {
        print("\(String(describing: error))")
    }
}

關閉並顯示控制器

func sign(_ signIn: GIDSignIn!, dismiss viewController: UIViewController!) {
    self.dismiss(animated: true, completion: nil)
}

func sign(_ signIn: GIDSignIn!, present viewController: UIViewController!) {
    self.present(viewController, animated: true, completion: nil)
}

像這樣調用登錄

func googleButtonClicked() {
    GIDSignIn.sharedInstance().delegate = self
    GIDSignIn.sharedInstance().uiDelegate = self
    GIDSignIn.sharedInstance().signIn()
}

解決方案實際上非常簡單,並且一直盯着我看

我從最初的 ViewController 實現了多個 segue。 然后我去掉了域名之前的電子郵件字符。 然后根據域名我進行了一定的轉場。

@UIApplicationMain 類 AppDelegate:UIResponder、UIApplicationDelegate、GIDSignInDelegate{

let userDefault  = UserDefaults()






func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
    if let error = error{
        print(error.localizedDescription)
        return


    }else{
        let userId = user.userID                  // For client-side use only!
        let idToken = user.authentication.idToken // Safe to send to the server
        let fullName = user.profile.name
        let givenName = user.profile.givenName
        let familyName = user.profile.familyName
        let email = user.profile.email
        let str = email
        let me = str?.count
        let int = (me!-9)
        let NewStr = str?.dropFirst(int)
        print(NewStr)




        guard let authentication = user.authentication else{return}
        let crendential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)
        Auth.auth().signInAndRetrieveData(with: crendential) {(result, error)in
            if error == nil {
                self.userDefault.set(true, forKey: "usersignedIn")
                self.userDefault.synchronize()
                if(NewStr == "gmail.com"){

                self.window?.rootViewController?.performSegue(withIdentifier: "Megue", sender: self)
                }
            }else {
                self.window?.rootViewController?.performSegue(withIdentifier: "Wegue", sender: self)
                print(error?.localizedDescription ?? "me")
            }
        }




    }


}



var window: UIWindow?




func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    FirebaseApp.configure()
    // Use Firebase library to configure APIs

    GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
    GIDSignIn.sharedInstance().delegate = self
    return true
}

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    return GIDSignIn.sharedInstance().handle(url,
                                             sourceApplication:options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
                                             annotation: [:])
}
func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

} 擴展字符串{

var length: Int {
    return count
}

subscript (i: Int) -> String {
    return self[i ..< i + 1]
}

func substring(fromIndex: Int) -> String {
    return self[min(fromIndex, length) ..< length]
}

func substring(toIndex: Int) -> String {
    return self[0 ..< max(0, toIndex)]
}

subscript (r: Range<Int>) -> String {
    let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)),
                                        upper: min(length, max(0, r.upperBound))))
    let start = index(startIndex, offsetBy: range.lowerBound)
    let end = index(start, offsetBy: range.upperBound - range.lowerBound)
    return String(self[start ..< end])
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM