0

According to the:

my approach is like:

AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    DispatchQueue.main.async {
        let username = "test@test.com"
        let password = "Test123"
        let serverUrl = URL(string: "http://test.com:9080")
        let realmUrl = URL(string: "realm://test.com:9080/~/realmtest")

        if let user = SyncUser.current {
            Realm.Configuration.defaultConfiguration.syncConfiguration = SyncConfiguration(user: user, realmURL: realmUrl!)
        } else {
            SyncUser.logIn(with: .usernamePassword(username: username, password: password, register: false), server: serverUrl!, onCompletion: { (user, error) in
                guard let user = user else {
                    print("Error: \(String(describing: error?.localizedDescription))")
                    return
                }
                Realm.Configuration.defaultConfiguration.syncConfiguration = SyncConfiguration(user: user, realmURL: realmUrl!)
            })
        }
    }

    return true
}

ViewController.swift

override func viewDidLoad() {
    super.viewDidLoad()
    print("SyncConfiguration: \(String(describing: Realm.Configuration.defaultConfiguration.syncConfiguration))")
    self.realm = try! Realm()
}

When I open app for the first time nothing happens but when I open app the second time, Realm works fine.

Whenever I open app, the printed SyncConfiguration is nil. No errors!

Searched here and there and can't find an answer...

gutaker
  • 181
  • 3
  • 10

1 Answers1

0

The problem is that you are using an async method to configure your Realm, but you don't call the print inside the completion handler of your method. You should only present your viewcontoller once your asynchronous call has finished.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • Yes, You are right. I haven't noticed that `SyncUser.login` method is actually logging the user in. I thought it's just a kind of config method to use later on. Anyway I have to do it the ugly way because the presented viewcontroller is my initial one. – gutaker Jun 28 '17 at 08:00