如何判断 FB.init() 何时完成?如何判断用户何时未连接应用程序启动?

Posted

技术标签:

【中文标题】如何判断 FB.init() 何时完成?如何判断用户何时未连接应用程序启动?【英文标题】:How to tell when FB.init() completed? How to tell if the user is not connected when to app starts? 【发布时间】:2013-08-12 18:19:57 【问题描述】:

我正在使用带有 Phonegap/Cordova 的 facebook 插件进行开发。我可能在 *** 和任何地方阅读了关于这个插件的每一篇文章或示例,但我仍然有这个未解决的问题。

    当应用程序启动时,我需要如果用户已经登录 --> 继续登录到主页。如果用户未登录 --> 显示“按下连接按钮登录”的屏幕

现在,当我的应用程序启动时,我会调用“FB.init”方法。问题是,我没有任何回调可以使用,所以我知道它何时完成,然后检查登录状态。

如果我在 FB.init 之前订阅 auth.statusChange 事件,那么我只会在用户已经登录时引发此事件。这还不够,因为我还需要知道他什么时候没有登录。

如果我在 FB.init 之后调用“FB.getLoginStatus”,它不起作用,因为这一切都是异步的,它会尝试在“fb.init()”完成之前获取登录状态。

换句话说,当应用启动时,我无法判断用户何时未登录。

谢谢你,立然。

【问题讨论】:

【参考方案1】:

好的,所以我现在用超时 + 小事解决了这个问题。 我真的不喜欢超时,但这是我目前为“未知”会话状态找到的唯一解决方案。这是我的代码:

// This event will rise when FB.init() completed, ONLY if the user is connected
        var statusChangeRaised = false;
        var statusChangeHandler = function(session) 
            statusChangeRaised = true;
            console.log('auth.statusChange event callback. session: ' + session.status);

            // We only want this handler one time
            FB.Event.unsubscribe('auth.statusChange', statusChangeHandler); 

            handleLoginStatus(d, session, true);
        ;
        FB.Event.subscribe('auth.statusChange', statusChangeHandler); 

        // Phonegap native plugin
        FB.init( appId : _FB_APP_ID,
              nativeInterface : CDV.FB,
              status: true,
              useCachedDialogs : false );

        // The callback can be trusted only if it say the user is NOT connected!
        //  * The scenario that the user is connected is covered by the auth.statusChange event
        FB.getLoginStatus(function(session) 
            console.log("getLoginStatus (just after init) callback. session: " + session.status);

            if (session.status === "notConnected") 
                statusChangeRaised = true;
                handleLoginStatus(d, session, false);
            
        );

        // The timeout will handle scenario that the user is "unknown", so the auth.StatusChange didn't rise
        //      and also the getLoginStatus cannot be truested,
        setTimeout(function ()  
            if (!statusChangeRaised) 
                FB.Event.unsubscribe('auth.statusChange', statusChangeHandler);

                FB.getLoginStatus(function(session) 
                    console.log('FB.getLoginStatus (inside timeout after FB.init) callback. session: ' + session.status);
                    handleLoginStatus(d, session, true);
                );
            
        , 6 * 1000); 

【讨论】:

以上是关于如何判断 FB.init() 何时完成?如何判断用户何时未连接应用程序启动?的主要内容,如果未能解决你的问题,请参考以下文章

writeToFile 如何判断何时完成

如何判断 UIWebView 何时完成渲染(未加载)?

如何判断 IPC::Run 作业何时完成

如何判断何时未使用谷歌位置自动完成建议?

如何判断 Microsoft Print to PDF 打印机驱动程序何时完成?

C#在遍历文件结构时如何判断所有线程或任务何时完成[重复]