我正在开发一个使用 Facebook SDK 登录的 ios 应用程序。
我已将 LogInViewController 设置为 Storyboard 中的初始 View Controller ,用户可从此处使用 FB 帐户登录。
我有另一个 ViewController,它会在用户登录后正确加载。
在 AppDelegate 文件中,我正在检查 currentAccessToken,如果它不是 nil,我将直接加载第二个 ViewController,因为用户已经登录。
但是,如果我退出应用程序并重新启动它,currentAccessToken 始终为 nil。仅当我按下主页按钮并在应用程序仍在后台运行时重新打开它时它才有效。
以下是代码中的详细信息:
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 的警告,因为 Storyboard 中没有针对它的 segue:
Warning: Attempt to present MapViewController whose view is not in the window hierarchy!
最佳答案
问题是因为您在调用之前调用了 FBSDKAccessToken.currentAccessToken()
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
您可以在调用上述行后随时检查访问 token 。
编辑:解释
上面这行让 Facebook SDK 处理 launchOptions 并提取必要的信息来识别和保留应用程序的用户。
在用户已经登录的情况下,这将简单地初始化 Facebook SDK,后者会根据持久数据登录用户。
关于ios - FBSDKAccessToken currentAccessToken 退出app后为nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32950937/