如果您的用户通过 Facebook 登录,如何以编程方式启动到另一个 viewController [英] How to programmatically launch into another viewController if your user is logged in through Facebook
问题描述
基本上,我有一个名为 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.
这是故事板中相关项目的外观,首先初始视图控制器在左侧,如果用户已登录,我希望应用程序从右侧的视图控制器启动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 代码
Swift 3 code
//检查上次访问令牌
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屋!