小编典典

FBSDKAccessToken currentAccessToken退出应用程序后为零

swift

我正在开发使用Facebook SDK登录的ios应用程序。我LogInViewController在情节提要中将a设置为初始View
Controller,用户从中使用FB帐户登录。

我有另一个ViewController,一旦用户登录,它将正确加载。

我正在检查AppDelegate文件currentAccessToken,如果不是nil,则直接加载第二个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!


阅读 452

收藏
2020-07-07

共1个答案

小编典典

问题是因为您在打电话FBSDKAccessToken.currentAccessToken()之前就在打电话

FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)

您可以在致电上述行后随时检查访问令牌。

编辑:解释

上面的代码行使Facebook SDK可以处理launchOptions并提取必要的信息,以识别并持久化应用程序的用户。

如果用户已经登录,则只需初始化Facebook SDK,然后再基于持久数据登录用户。

2020-07-07