firebase身份验证侦听器和网络连接

时间:2017-06-02 16:43:18

标签: ios swift firebase firebase-authentication

测试用例:

在我的场景中,我在Xcode中初始化我的应用程序,登录到firebase并运行我的应用程序 成功。然后我在Xcode中停止调试器,然后"关闭Wifi"上 我的MAC。然后我再次在Xcode中初始化我的应用程序。

在调试器中,我看到我的代码初始化了一个身份验证监听器和 根据以前缓存的经过身份验证的用户信息的值进行初始化。

我还在控制台日志中看到以下异常。

2017-06-02 09:29:21.281 MusicPoll [7053] [Firebase / Core] [I-NET901017]遇到网络错误。代码,错误:-1009,错误域= NSURLErrorDomain代码= -1009" Internet连接似乎处于脱机状态。" UserInfo = {NSUnderlyingError = 0x60800005f7d0 {错误域= kCFErrorDomainCFNetwork代码= -1009"(null)" UserInfo = {_ kCFStreamErrorCodeKey = 50,_kCFStreamErrorDomainKey = 1}},NSErrorFailingURLStringKey = https://play.googleapis.com/log,NSErrorFailingURLKey = https://play.googleapis.com/log,_ kCFStreamErrorDomainKey = 1,_kCFStreamErrorCodeKey = 50,NSLocalizedDescription = Internet连接似乎处于脱机状态。}

由于我没有连接到网络,我想检测一下 条件并要求用户检查他/她的网络连接,然后重试。

我的问题是我应该使用哪种Firebase方法来检查网络连接并可能获得错误。 (我无法找到可能的错误代码 在听众的回调中返回。)

我的代码:

...

fileprivate var authListener:FIRAuthStateDidChangeListenerHandle!

FUIAuth.defaultAuthUI()?. providers = [FUIGoogleAuth()]

authListener = FIRAuth.auth()?addStateDidChangeListener {[weak self](auth:FIRAuth,user:FIRUser?)in

        guard let strongSelf = self else { return }

        if let activeUser = user {

            strongSelf.hasUserBeenAuthenticated = true
            strongSelf.user = activeUser

        } else {

            strongSelf.hasUserBeenAuthenticated = false
            strongSelf.user = nil
        }

        print("\nFirebaseMgr[setupAuthorization]: hasUserBeenAuthenticated = \(strongSelf.hasUserBeenAuthenticated), user = \(String(describing: strongSelf.user))")
   }

1 个答案:

答案 0 :(得分:0)

您可以使用Firebase的FIRDatabase.database()。reference(withPath:“。info / connected”)方法检查用户的互联网连接状态。此方法将观察网络连接的任何变化。这是一个例子:

    //this is a strong reference to the internet connection handle
    var internetConnectionHandle: UInt!


    //I have created the observer for internet connectivity in viewWillAppear
    override func viewWillAppear(_ animated:Bool) {
         let connectedRef = FIRDatabase.database().reference(withPath: ".info/connected")

    internetConnectionHandle = connectedRef.observe(.value, with: { snapshot in

        if let _ = snapshot.value as? Bool {

            //use is connected to the internet. 


        }
        else {

           //user is not connected to the internet. Ask the user to check his/her network connection and try again
        }
    })