Sync Session.connectionState appears not to work


(Jerry Porter) #1

Hello,

As stated in the title syncSession.connectionState does not appear to work.
I am using realm/realm-cocoa == 3.14.1 and ROS v3.18.5

Below is a simple POC class.

I am expecting in the connectionStateObserver = syncSession.observe(.connectionState, options: [.initial]) { object, change in closure that when I start and stop my realm, I should see different state changes, however, I am only seeing disconnected.

Am I missing something?

regards,
Jerry
import UIKit
import RealmSwift
import Realm

class ConnectivityStatus: NSObject {

var syncSession: SyncSession!
var connectionStateObserver: NSKeyValueObservation?
var realm: Realm!

override init() {
    super.init()
    
    setupRealm()
}

private func setupObservation(realm: Realm) {
    guard let syncSession = realm.syncSession else {
        print("Failed to create sync session for our realm")
        return
    }
    
    self.syncSession = syncSession
    
    connectionStateObserver = syncSession.observe(\.connectionState, options: [.initial]) { object, change in
        print("Realm Connection object: \(object.debugDescription)")

        switch(syncSession.connectionState) {
        case .disconnected :
            print("Connection state: disconnected")
        case .connected :
            print("Connection state: connected")
        case .connecting :
            print("Connection state: connecting")
        }
    }
}

private func setupRealm() {
    let realmUrl = URL(string: REALM_CONFIGURATION.url)!
    let authUrl = URL(string: REALM_CONFIGURATION.authUrl)!
    
    let creds = SyncCredentials.usernamePassword(
        username: REALM_CONFIGURATION.user,
        password: REALM_CONFIGURATION.password,
        register: false
    )

    SyncUser.logIn(with: creds, server: authUrl, onCompletion: { (user, err) in
        if err != nil {
            print("Failed to log into Realm:\n \(String(describing: err))")
            //ideally we set up some real retry logic here
            DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + 5.0) {
                self.setupRealm()
            }
            return
        }
        
        guard let currentUser = user else {
            print("user is nil")
            return
        }
        
        print("Logged into Realm")
        
        do {
            let syncConfig = currentUser.configuration(realmURL: realmUrl, fullSynchronization: true)
            self.realm = try Realm(configuration: syncConfig)

            self.setupObservation(realm: self.realm)
        } catch let error {
            print("Failed to initialize Realm:\n \(error)")
        }
    })
}

private func logoutAllUsers(){
    for user in SyncUser.all {
        print("Logging out user: \(user.key) - \(user.value)")
        user.value.logOut()
    }
}

}