为Chat App中的每个用户创建Realm DB

时间:2017-05-18 15:43:06

标签: swift realm realm-mobile-platform

这个用于发送消息并将其保存到realm db

 var messageIndex = try! Realm().objects(MessageRealm.self).sorted(byKeyPath: "timeStamp")

 func didPressSend(text: String) {
    if self.inputContinerView.inputTextField.text! != "" {
        let messageDB = MessageRealm()
        let realm = try! Realm()
        let userRealm = UsersRealm()

        messageDB.textDownloadded = text
        messageDB.fromId = user!.fromId
        messageDB.timeStamp = Date()
        print(messageDB)

        try! realm.write ({
            print(realm.configuration.fileURL)
            userRealm.msgs.append(messageDB)
            //realm.create(MessageRealm.self, value: ["textDownloadded": text, "fromId": user!.fromId, "timeStamp": Date()])
        })
        if let userTitleName = user?.toId {
            print(userTitleName)
            OneMessage.sendMessage(text, thread: "AAAWatree", to: userTitleName, isPhoto: false, isVideo: false, isVoice: false, isLocation: false, timeStamp: date, completionHandler: { (stream, message) in
                DispatchQueue.main.async {
                    OneMessage.sharedInstance.deleteCoreDataMessage()
                }
                self.inputContinerView.inputTextField.text! = ""
            })
        }
    }
}

这用于在收到消息时尝试保存用户(发送ID)

  let realm = try! Realm()
                    userData.sender = sender
                    userData.toId = toUser
                    print(userData.sender)
                    print(userData.toId)
                        try! realm.write ({
                            realm.add(userData, update: true)

                        })

这是我的Realm对象类

class MessageRealm: Object {

dynamic var textDownloadded = String()
dynamic var imageDownloadded = NSData()
dynamic var videoDownloadded = String()
dynamic var voiceDownloadded = String()
dynamic var fromId = String()
dynamic var timeStamp = Date()
dynamic var messageId = NSUUID().uuidString
let userSelect = List<UsersRealm>()
override class func primaryKey() -> String? {
    return "messageId"
}

}

class UsersRealm:Object {

dynamic var sender = String()
dynamic var fromId = String()
dynamic var toId = String()
dynamic var lastMessage = String()
dynamic var timeStamp = Date()
dynamic var profileImage = NSData()
let msgs = List<MessageRealm>()
override class func primaryKey() -> String {
    return "sender"
}    
}

发送和接收是好的,它保存到领域数据库,但所有任何用户发送的消息我在一个用户我想要为每个用户分离有他的发送和recive数据库我想念这里但我不知道我尝试搜索没有什么是长期的问题,但我无法弄清楚解决方案

抱歉我的一周英语 谢谢

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的情况,那么您将为所有用户使用单个领域网址,这就是为什么所有客户都拥有相同数据的原因。您应该为对话创建一个单独的领域,并在参与该聊天的用户之间共享。请在https://realm.io/docs/swift/latest/#access-control了解有关在我们的文档中分享领域的更多信息。