基于查询的领域遇到问题

时间:2018-06-09 03:15:14

标签: swift realm

对不起,我的主题不是很具体。

我正在管理我的领域中的多个用户并遇到一些问题。我有一个用户注册他们的电子邮件和名称,然后当领域登录并创建SyncUser时,我创建了一个新的YpbUser对象,其中包含电子邮件,名称和SyncUser.current.identity YpbUser.id 1}}。

当用户登录时,我想使用他们的电子邮件查询他们的电子邮件是否存在YpbUser。我是这样做的,所以将来如果有人使用用户名/密码然后使用Google身份验证(尚未实现),那些SyncUser可以转到同一个YpbUser

下面是我检查现有YpbUser的代码,以及我的领域设置代码。我遇到的问题是,即使该用户存在,我也常常(但并非总是)找不到YpbUser(我正在查看领域工作室中的YpbUser列表有电子邮件的用户肯定在那里!)

existingUser(for:in:)内进行检查,users通常为0,但有时不为零。

我认为这个问题存在于某个地方,我只是猜测如何使用SyncSubscription.observe

请帮帮忙?

    fileprivate func openRealmWithUser(user: SyncUser) {
        DispatchQueue.main.async { [weak self] in
            let config = user.configuration(realmURL: RealmConstants.realmURL, fullSynchronization: false, enableSSLValidation: true, urlPrefix: nil)
            self?.realm = try! Realm(configuration: config)

            let songSub = self?.realm?.objects(Song.self).subscribe()
            let usersSub = self?.realm?.objects(YpbUser.self).subscribe()

            self?.usersToken = usersSub?.observe(\.state, options: .initial) { state in
                if !(self?.proposedUser.email.isEmpty)! {
                    self?.findYpbUser(in: (self?.realm)!)
                }
            }
            self?.performSegue(withIdentifier: Storyboard.LoginToNewRequestSegue, sender: nil)
        }
    }

    fileprivate func findYpbUser(in realm: Realm) {
        if proposedUser != YpbUser() { // self.proposedUser.email gets set from the login method
            let existingUser = YpbUser.existingUser(for: proposedUser, in: realm)
            guard existingUser == nil else { // If we find the YpbUser, set as current:
                try! realm.write {
                    pr("YpbUser found: \(existingUser!)")
                    YpbUser.current = existingUser }
                return
            }
            pr("YpbUser not found.") // i.e., SyncUser set, but no YpbUser found. i.e., creating a new YpbUser
            createNewYpbUser(for: proposedUser, in: realm)
        }
    }

extension YpbUser {
    class func existingUser (for proposedUser: YpbUser, in realm: Realm) -> YpbUser? {
        let users = realm.objects(YpbUser.self)
        let usersWithThisEmail = users.filter("email = %@", proposedUser.email)
        if let emailUser = usersWithThisEmail.first {
            return emailUser
        }
        return nil
    }
}

0 个答案:

没有答案