如果用户通过Facebooklogin,如何以编程方式启动到另一个viewController

基本上我有一个名为facebookLogin.swift的类,login页面和ViewController.Swift的主页。 我已经正确编码所有的Facebooklogin的东西,它的一切工作,我可以login和注销FBSDK提供的button以及我定义的自定义button。 但是,我不知道如何进入ViewController.swift页面,如果用户login。

这里是facebookLogin.swift代码:

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文件的相关代码:

 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类的第一个应用程序函数中,我find了另一个关于使用这个代码的stackoverflow的教程。 我input代码并将语法转换为swift3,但是当我启动它时,应用程序会中断。 这意味着它知道我login,但由于某种原因,segue不加载,它打破了应用程序。 我得到的错误是线程1:sigabrt。

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

你的代码似乎没问题。 您应该考虑在Storyboarddevise屏幕的Identity部分下检查您的ViewController的Storyboard ID。 你应该给Storyboard ID“ViewController”。 根据您的代码,login屏幕的Storyboard ID应该是“facebookLogin”。

您当前的访问令牌为零。 尝试检查真实的设备,因为最新的FBSDK不在模拟器中存储访问令牌。 它将在控制台中打印“由于模拟器错误而回退到从NSUserDefaults加载访问令牌”

—-编辑—-

这里如果你的当前访问令牌是零而不是login屏幕。 根据您的要求更改以下条件

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

根据需要更改initialViewController。

—-更新—-

你可以忽略这个警告,当使用iOS模拟器时,它在FacebookSDK中被硬编码。 SDK确实包含一个错误,尽pipe它阻止了模拟器caching访问令牌。

您可以通过在FBSDKKeychainStore.m:94和FBSDKKeychainStore.m:135之前添加以下行来解决此问题:

 let key = String(format: "%@_fix", key) UserDefaults().set(key, forKey: value) 

Swift 3代码

//检查最后的AccesToken

  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 } } }