我正在开发使用Facebook SDK登录的ios应用程序。
我已在 Storyboard 中将LogInViewController
设置为初始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 中没有针对它的安全保护措施:最佳答案
问题是因为您在调用之前先调用FBSDKAccessToken.currentAccessToken()
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
您可以在致电上述行后随时检查访问 token 。
编辑:说明
上面的代码行使Facebook SDK可以处理launchOptions并提取必要的信息,以识别并持久化应用程序的用户。
如果用户已经登录,则只需初始化Facebook SDK,然后再基于持久数据登录用户。
关于ios - FBSDKAccessToken currentAccessToken退出应用程序后为零,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32950937/