How do I detect online/offline state of synced realm (iOS/Swift)


#1

When my app first starts up, I want to check for downloading to complete before continuing. But if I cannot reach the realm server for some reason (bad network connection, VPN blocking it, etc) the progress notification will just hang.

These values are the same with or without a WiFi connection when I test, so how do I detect whether or not to check for download progress?

  • user.state is RLMSyncUserStateActive
  • session.state is RLMSyncSessionStateActive
  • session.connectionState is RLMSyncConnectionStateDisconnected

Here is the method I am using:

    private func waitForDownload(user: SyncUser, completion: @escaping ((Result<Void>) -> Void)) {
        guard let session = user.allSessions().first else {
            completion(.failure(TherexRxRealmError.failureToGetSessionForDownload))
            return
        }

        NSLog("DBG: user.state=\(user.state.rawValue)")
        NSLog("DBG: session.state=\(session.state.rawValue)")
        NSLog("DBG: session.connectionState=\(session.connectionState.rawValue)")

        sessionDownloadNotificationToken = session.addProgressNotification(
            for: .download,
            mode: .forCurrentlyOutstandingWork) { [unowned self] progress in
                NSLog("DBG: UserDataSource sync download progress=\(progress.fractionTransferred)")
                if progress.isTransferComplete {
                    self.sessionDownloadNotificationToken?.invalidate()
                    self.sessionDownloadNotificationToken = nil
                    completion(.success(()))
                }
        }
    }

#2

@dwsjoquist RLMSyncSession.connectionState will tell you if you are currently connected to ROS or not.

You can also use SyncSession.observe and which works like a notification token and will give you a connectionState == .connected OR connectionState == .disconnected