如果用户已使用facebook登录,则使用swift调用segue

时间:2016-04-11 13:29:40

标签: ios swift facebook facebook-login

我一直在关注如何使用swift登录facebook。 http://letsbuildthatapp.com/2016/03/26/swift-facebook-login-sdk-and-getting-users-email/

但是,当我通过双击主页按钮并向上滑动应用程序来关闭应用程序时,我看到我的登录屏幕有一个区别。按钮的文本已更改为注销。

我想要做的是自动跳过该登录页面并执行此segue:self.performSegueWithIdentifier("redirectAfterLogin", sender: self)

我遇到过这篇文章但我自己无法解决这个问题,现在我有点困惑。 How to check if user is logged in with FBSDKLoginKit in iOS?

下面你可以看到我的AppDelegate.swift和LoginVC.swift文件。我该如何解决这个问题?

AppDelegate.swift

import UIKit



@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CNPPopupControllerDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)

        return true
    }

    func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
        return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: 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 throttle down OpenGL ES frame rates. 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 inactive 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:.
    }


}

LoginVC.swift

import UIKit
import KASlideShow


class LoginVC: UIViewController, KASlideShowDelegate, FBSDKLoginButtonDelegate  {

    let loginButton: FBSDKLoginButton = {
        let button = FBSDKLoginButton()
        button.readPermissions = ["email"]
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // do stuff here

        view.addSubview(loginButton)
        loginButton.center = view.center
        loginButton.readPermissions = ["public_profile", "email", "user_friends"]
        loginButton.delegate = self // Remember to set the delegate of the loginButton

        if let token = FBSDKAccessToken.currentAccessToken() {
            fetchProfile()
        }

        if FBSDKAccessToken.currentAccessToken() != nil {
            print("1")
            self.performSegueWithIdentifier("redirectAfterLogin", sender: self)
        }


    }

    func fetchProfile(){
        print("fetching profile..")
        let params = ["fields": "email, first_name, last_name, picture.type(large)"]
        FBSDKGraphRequest(graphPath: "me", parameters: params).startWithCompletionHandler{ (connection, result, var error) -> Void in
            if error != nil {
                print (error)
                return
            }

            if let email = result["email"] as? String {
                print(email)
                NSUserDefaults.standardUserDefaults().setObject(email, forKey: "email")
            }

            if let first_name = result["first_name"] as? String {
                print(first_name)
                NSUserDefaults.standardUserDefaults().setObject(first_name, forKey: "first_name")
            }

            if let last_name = result["last_name"] as? String {
                print(last_name)
                NSUserDefaults.standardUserDefaults().setObject(last_name, forKey: "last_name")
            }

            if let picture = result["picture"] as? NSDictionary, data=picture["data"] as? NSDictionary, url=data["url"] as? String {
                print(url)
                NSUserDefaults.standardUserDefaults().setObject(url, forKey: "url")
            }

            NSUserDefaults.standardUserDefaults().synchronize()
            print(result) // this prints whole FBSDKGraphRequest API response
        }

    }

    func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
        print("login completed")
        fetchProfile()
        self.performSegueWithIdentifier("redirectAfterLogin", sender: self)
    }

    func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {

    }

    func loginButtonWillLogin(loginButton: FBSDKLoginButton!) -> Bool {
        return true
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

1 个答案:

答案 0 :(得分:1)

您需要做的是appDelegate

application(application: UIApplication, didFinishLaunchingWithOptions launchOptions:

if let root = UIApplication.sharedApplication().windows[0].rootViewController as? UINavigationController {
     if CONDITION {
          root.viewControllers = [USER_HOMEPAGE]
     } else {
          root.viewControllers = [USER_LOGIN]
     }
}