如果您的用户通过Facebook登录,如何以编程方式启动另一个viewController [英] How to programmatically launch into another viewController if your user is logged in through Facebook

查看:471
本文介绍了如果您的用户通过Facebook登录,如何以编程方式启动另一个viewController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有一个名为facebookLogin.swift的类,登录页面和ViewController.Swift主页。我已经正确编码了所有的Facebook登录信息,它一切正常,我可以登录并注销与FBSDK提供的按钮以及我定义的自定义按钮。但是,如果用户登录,我不知道如何去ViewController.swift页面。

Basically I have one class called facebookLogin.swift, the login page, and ViewController.Swift the homepage. I have correctly coded all the Facebook login stuff and it all works, I can log in and log out with both the button the FBSDK provides as well as the custom button I have defined. However, I can not figure out how to go to the ViewController.swift page if the user is logged in.

这是facebookLogin.swift代码:

Here is the facebookLogin.swift code:

import UIKit
import FBSDKCoreKit
import FBSDKLoginKit

class facebookLogin: UIViewController, FBSDKLoginButtonDelegate {
    var loginStatus = false;

    @IBOutlet weak var facebookOutlet: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        super.viewDidLoad()
        let loginButton  = FBSDKLoginButton()
        view.addSubview(loginButton)
        loginButton.center = view.center
        loginButton.delegate = self;
        loginButton.readPermissions = ["email","public_profile"]
    }

    @IBAction func facebookAction(_ sender: Any) {
        customFBLogin()
        if (FBSDKAccessToken.current() != nil) {
            NSLog("it works")
        }
    }

    func customFBLogin() {
        FBSDKLoginManager().logIn(withReadPermissions: ["email","public_profile"], from: self) { (result, err) in
            if err != nil {
                print("Facebook Login Error Failed \(err)")
                return;
            }
            self.showEmailAddress();
            self.loginStatus = true;
        }
    }



    func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
        print("Did log out of Facebook")
    }

    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
        if error != nil {
            print(error)
            return;
        } else {
            print("Successfuly logged into Facebook");
            showEmailAddress()

        }
    }

    func showEmailAddress() {
        FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start(completionHandler: { (connection, result, err) in

            if err != nil {
                print("Failed to start graph request \(err)")
                return;
            }
            print(result)

        })
    }


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


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

是AppDelegate.swift文件中的相关代码:

Here is the relevant code from the AppDelegate.swift file:

import UIKit
import CoreData
import Firebase
import FBSDKCoreKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FIRApp.configure()
        FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)

        let mainStoryBoard = UIStoryboard.init(name: "Main", bundle: nil)
        self.window = UIWindow(frame: UIScreen.main.bounds)
        var initialViewController: UIViewController

        if(FBSDKAccessToken.current() != nil) {
            let vc = mainStoryBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
            initialViewController = vc
        } else{
            initialViewController = mainStoryBoard.instantiateViewController(withIdentifier: "facebookLogin")
        }

        self.window?.rootViewController = initialViewController

        self.window?.makeKeyAndVisible()

        return true
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        let handled = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String!, annotation: options[UIApplicationOpenURLOptionsKey.annotation])

        return handled;
    }

在AppDelegate.swift类的第一个应用程序函数中,我找到了另一个关于stackoverflow的教程,建议使用此代码。我输入了代码并将其转换为swift3,但是当我启动它时,应用程序就会中断。这意味着它知道我已经登录,但由于某种原因,segue没有加载,它会打破应用程序。我得到的错误是线程1:sigabrt。

In the first application function in the AppDelegate.swift class, I have found another tutorial on stackoverflow which suggested using this code. I inputted the code and converted the syntax to swift3, but the app breaks when I launch it. This means that it knows that I am logged in but for some reason the segue does not load and it breaks the app. The error I get is Thread 1: sigabrt.

这是故事板中相关项目的外观,首先是初始视图控制器在左边,如果用户登录我希望应用程序从右边的viewController开始
1

Here is how the relevant items in the story board look, at first the initial view Controller is on the left and if the user is logged in I want the app to start from the viewController on the right 1

推荐答案

Swift 3代码


如果让accessToken = AccessToken.current {$ b



    if let accessToken = AccessToken.current {
        print("Last AccesToken -\(accessToken)")

        // Redirect to next screen
        self.performSegue(withIdentifier:"NextScreen", sender: self)
    }
    else {

        let loginManager = LoginManager()
        loginManager.loginBehavior = LoginBehavior.web
        loginManager.logIn([ .publicProfile , .email, .userFriends], viewController: self) { loginResult in
            switch loginResult {

            case .failed(let error):
                print(error)
                break
            case .cancelled:
                print("User cancelled login.")
                break
            case .success(let grantedPermissions, let declinedPermissions, let accessToken):
                print("Logged in! \(grantedPermissions) \(accessToken) \(declinedPermissions)")

                // Save Current UserInfo
                let params = ["fields":"id,name,email,picture"]
                let graphRequest = GraphRequest(graphPath: "me", parameters: params)
                graphRequest.start { (urlResponse, requestResult) in
                    switch requestResult {
                    case .failed(let error):
                        print(error)
                    case .success(let graphResponse):
                        if let responseDictionary = graphResponse.dictionaryValue {

                            print("\(String(describing: graphResponse.dictionaryValue))")

                            UserDefaults.standard.set(responseDictionary, forKey: "userInfo")
                        }
                    }
                }

                self.performSegue(withIdentifier: "NextScreen", sender: self)
                break
            }
        }
    }

这篇关于如果您的用户通过Facebook登录,如何以编程方式启动另一个viewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆