【发布时间】:2016-01-02 05:56:27
【问题描述】:
我正在开发一个使用 Facebook SDK 登录的 ios 应用程序。
我在 Storyboard 中将LogInViewController 设置为初始视图控制器,用户使用 FB 帐户登录。
我有另一个 ViewController,一旦用户登录,它就会正确加载。
在 AppDelegate 文件中,我正在检查 currentAccessToken,如果它不为零,我将直接加载第二个 ViewController,因为用户已经登录。
但是,如果我退出应用程序并重新启动它,currentAccessToken 始终为零。仅当我按下主页按钮并在应用程序仍在后台运行时重新打开它时才有效。
以下是代码中的详细信息:
AppDelegate.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.customNavigationBar()
if (!isIcloudAvailable()) {
self.displayAlertWithTitle("iCloud", message: "iCloud is not available." +
" Please sign into your iCloud account and restart this app")
return true
}
if (FBSDKAccessToken.currentAccessToken() != nil) {
self.instantiateViewController("MapViewController", storyboardIdentifier: "Main")
}
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}
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) {
FBSDKAppEvents.activateApp()
}
func applicationDidBecomeActive(application: UIApplication) {
FBSDKAppEvents.activateApp()
}
LogInViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
// Listen to the Facebook notification and when received, execute func handleFBSessionStateChangeWithNotification
NSNotificationCenter.defaultCenter().addObserver(self, selector:"handleFBSessionStateChangeWithNotification:", name: "SessionStateChangeNotification", object: nil)
}
func handleFBSessionStateChangeWithNotification(notification: NSNotification) {
// Switch to MapViewController when logged in
if ((FBSDKAccessToken.currentAccessToken()) != nil) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let mapViewController = storyboard.instantiateViewControllerWithIdentifier("MapViewController") as! MapViewController
self.presentViewController(mapViewController, animated: false, completion: nil)
}
}
我不知道它是否相关,但我也收到了MapViewController 的警告,因为情节提要中没有对其进行转义:
警告:尝试呈现其视图不在视图中的 MapViewController 窗口层次结构!
【问题讨论】:
-
FBAccessToken.currentAccessToken 需要一些时间来填充。您应该使用 sessionStateChangedNotification 等待它可用(就像您已经完成的那样)。
-
感谢您的回答。需要多少时间?这意味着如果用户很快退出应用程序,他将需要重新登录?我记得在以前的 FBSDK 版本中,有一个缓存访问令牌的检查,现在我不知道该怎么做。
-
我尝试将 sessionStateChangedNotification 放在 LoginViewController 的 viewDidAppear 中,但没有任何改变。
标签: ios swift facebook-login facebook-access-token fbsdk