基本上我有一个名为facebooklogin.swift,登录页面和viewController.swift主页的类。我已经正确地编码了所有Facebook登录功能,所有这些都可以使用,我可以使用FBSDK提供的按钮以及我定义的自定义按钮登录并注销。但是,如果用户已登录,我无法弄清楚如何转到ViewController.swift页面。
这是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类中的第一个应用程序功能中,我在Stackoverflow上找到了另一个使用此代码的教程。我输入了代码并将语法转换为swift3,但是当我启动时,该应用程序会断开。这意味着它知道我已登录,但是由于某种原因,SEGUE不会加载并打破了应用程序。我得到的错误是线程1:sigabrt。
这是故事板中的相关项目的外观,首先,初始视图控制器在左侧,如果用户已记录在我希望该应用程序中,请从右侧的ViewController开始1
您的代码似乎还可以。您应该考虑在故事板设计屏幕中的身份部分中查看ViewController的故事板ID。您应该将故事板ID作为" ViewController"。登录屏幕的故事板ID应根据您的代码为" FacebookLogin"。
swift 3代码
//检查Last 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
}
}
}