使用GIDSignIn登录后更改视图

时间:2020-06-11 18:22:30

标签: ios swift

在使用google(GidSignIn)登录后,我无法找到一种可行的或最新的解决方案,无法将我的视图从登录页面切换到默认的视图控制器。一切都可以成功登录。我不知道问题是否出在我从登录视图控制器到容器视图的问题。我有一个从LoginScreenVC到包含我的标签栏控制器和侧边栏菜单的Container视图的推送选项。到目前为止,我已经尝试使用

来实现登录后切换视图
 if (GIDSignIn.sharedInstance().hasPreviousSignIn()){
            print("signed in")
            performSegue(withIdentifier: "LoginToContainerSegue", sender: self)

        }

...在我的loginVC中的viewdidload中。 我还尝试通过ibaction按钮使用它。

    @IBAction func signInButton(_ sender: AnyObject) {

        GIDSignIn.sharedInstance()?.signIn()
 performSegue(withIdentifier: "LoginToContainerSegue", sender: self)

}

如果我将performegue放在viewdidload中,则登录后不会执行任何操作。如果将performegue放在按钮功能中,它将在切换谷歌登录webview之前切换视图。使用我的appdelegate代码,如果我关闭并重新打开我的应用程序,它将在登录后显示默认的容器视图,但就像我说的那样,它不能正常正常运行。

这是我来自AppDelegate的代码:


import UIKit
import GoogleSignIn

@UIApplicationMain
// [START appdelegate_interfaces]
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {

  // [END appdelegate_interfaces]
  var window: UIWindow?

  // [START didfinishlaunching]
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Initialize sign-in
    GIDSignIn.sharedInstance().clientID = "myid.apps.googleusercontent.com"
    GIDSignIn.sharedInstance().delegate = self
    GIDSignIn.sharedInstance()?.restorePreviousSignIn()


    if GIDSignIn.sharedInstance().hasPreviousSignIn() {
                /* Code to show tab bar controller */
                print("user is signed in")
                let sb = UIStoryboard(name: "Main", bundle: nil)
        if let ContainerVCC = sb.instantiateViewController(withIdentifier: "ContainerVC") as? UIViewController {
                    window!.rootViewController = ContainerVCC
                }
            } else {
                print("user is NOT signed in")
                /* code to show login VC */
                let sb = UIStoryboard(name: "Main", bundle: nil)
        if let LoginScreenVCC = sb.instantiateViewController(withIdentifier: "LoginScreenVC") as? UIViewController {
                    window!.rootViewController = LoginScreenVCC
                }
        }

    return true
  }
  // [END didfinishlaunching]
  // [START openurl]
  func application(_ application: UIApplication,
                   open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    return GIDSignIn.sharedInstance().handle(url)
  }
  // [END openurl]
  // [START openurl_new]
  @available(iOS 9.0, *)
  func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
    return GIDSignIn.sharedInstance().handle(url)
  }
  // [END openurl_new]
  // [START signin_handler]
  func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
            withError error: Error!) {
    if let error = error {
      if (error as NSError).code == GIDSignInErrorCode.hasNoAuthInKeychain.rawValue {
        print("The user has not signed in before or they have since signed out.")
      } else {
        print("\(error.localizedDescription)")
      }
      // [START_EXCLUDE silent]
      NotificationCenter.default.post(
        name: Notification.Name(rawValue: "ToggleAuthUINotification"), object: nil, userInfo: nil)
      // [END_EXCLUDE]
      return
    }



    // Perform any operations on signed in user here.
    // 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
    // [START_EXCLUDE]
    NotificationCenter.default.post(
      name: Notification.Name(rawValue: "ToggleAuthUINotification"),
      object: nil,
      userInfo: ["statusText": "Signed in user:\n\(fullName!)"])
    // [END_EXCLUDE]
  }
  // [END signin_handler]
  // [START disconnect_handler]
  func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!,
            withError error: Error!) {
    // Perform any operations when the user disconnects from app here.
    // [START_EXCLUDE]
    NotificationCenter.default.post(
      name: Notification.Name(rawValue: "ToggleAuthUINotification"),
      object: nil,
      userInfo: ["statusText": "User has disconnected."])
    // [END_EXCLUDE]
  }
  // [END disconnect_handler]
}
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:.
 }

这是我的LoginScreenVC中的代码

import UIKit
import GoogleSignIn
import CoreData
import AVKit

class LoginScreenVC: UIViewController {

    var videoPlayer: AVPlayer?
    var videoPlayerLayer: AVPlayerLayer?

    // DEBUG - REPEAT VIDEO
    //var player: AVPlayer!
    //
    //NotificationCenter.default.addObserver(forName: AVPlayerItemDidPlayToEndTime, object: self.player.currentItem, queue: .main) { [weak self] _ in
      // self?.player?.seek(to: CMTime.zero)
     //  self?.player?.play()
   // }

    override func viewDidLoad() {
    super.viewDidLoad()


        GIDSignIn.sharedInstance().presentingViewController = self


        if (GIDSignIn.sharedInstance().hasPreviousSignIn()){
            print("signed in")
            performSegue(withIdentifier: "LoginToContainerSegue", sender: self)

        }

 // change view if already logged in

    }
    // AVPLAYER

    override func viewWillAppear(_ animated: Bool) {
        //set up video in background
        setUpVideo()
    }
    func setUpVideo() {
       let bundlePath = Bundle.main.path(forResource: "mielatovideo1", ofType: "mp4")
        guard bundlePath != nil else {
            return
        }
        let url = URL(fileURLWithPath: bundlePath!)
        let item = AVPlayerItem(url: url)

        videoPlayer = AVPlayer(playerItem: item)

        videoPlayerLayer = AVPlayerLayer(player: videoPlayer!)

        videoPlayerLayer?.frame = CGRect(x: -self.view.frame.size.width*1.5, y: 0, width: self.view.frame.size.width*4, height: self.view.frame.size.height)

        view.layer.insertSublayer(videoPlayerLayer!, at: 0)

        videoPlayer?.playImmediately(atRate: 0.3)

       videoPlayer?.isMuted = true

}


    @IBAction func signInButton(_ sender: AnyObject) {

        GIDSignIn.sharedInstance()?.signIn()

}



}

任何帮助将不胜感激。

0 个答案:

没有答案