目标:
当我使用MessageListController
从didSelectRowAt
中的聊天消息列表中选择一条消息时,我希望在下一个ChatDetailController
中打开的聊天会话与所选的同一个会话相匹配。明显。
我正在使用WatchKit,但这个iOS图像也是如此。选择Sophia的消息并打开与Sophia的聊天。
我想从我的模型中传递json“message_id”,即chatMessageId
属性。我已经从chatMessageId
MessageModel
传递ChatDetailController
用这条线presentController(withName: "ChatDetailController", context: messageContext)
这是使用messageContext
打印出的传递数据。
传递上下文:可选(HTWatch_Extension.MessageModel(合作伙伴:“9859”,昵称:“Marco”,消息:“你见过的是狗吗?”,城市:“马德里”,countryBadgeImageURL:https://i.imgur.com/PJcyle7.jpg,messageListImageURL:https://i.imgur.com/PJcyle7.jpg,chatMessageId:“Tva9d2OJyWHRC1AqEfKjclRwXnlRDQ “,状态:”离线“))
下一步是什么?如何告诉ChatDetailController
使用与所选行匹配的对话填充其表?
MessageListController
// ...code...
let messageObject = [MessageModel]()
//var chatObject = [ChatModel]()
// ...code...
override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) {
var messageContext = messageObject[rowIndex]
var chatContext = chatObject[rowIndex]
do {
guard let fileUrl = Bundle.main.url(forResource: "Chats", withExtension: "json") else {
print("File could not be located")
return
}
let data = try Data(contentsOf: fileUrl)
let decoder = JSONDecoder()
let msg = try decoder.decode([ChatModel].self, from: data)
self.chatObject = msg
} catch let error {
print(error)
}
// I got part of this line from a previous question, but these property types do not match.
// No matter what chatObject I create I cannot access it/assign it.
// Also I do not want to mutate messageContext which Xcode is telling me to do.
messageContext.chatMessageId = (chatObject as AnyObject).filter { (dictionaryTemp:[String:String]) -> Bool in
return dictionaryTemp["message_id"] == chatContext.chatMessageId
}
// WatchKit's model presentation method.
presentController(withName: "ChatDetailController", context: messageContext)
}
ChatDetailController
var chats: [ChatModel] = []
var messageModel: MessageModel? {
didSet {
guard let model = messageModel else { return }
partnerLabel.setText(model.nickname)
}
}
override func awake(withContext context: Any?) {
super.awake(withContext: context)
if let message = context as? MessageModel {
self.messageModel = message
print("Passed context: \(String(describing: messageModel))")
} else {
print("Passed context error: \(String(describing: context))")
}
do {
guard let fileUrl = Bundle.main.url(forResource: "Chats", withExtension: "json") else {
print("File could not be located")
return
}
let data = try Data(contentsOf: fileUrl)
let decoder = JSONDecoder()
let msg = try decoder.decode([ChatModel].self, from: data)
self.chats = msg
} catch let error {
print(error)
}
DispatchQueue.main.async(execute: {
self.setupTable(chatMessageArray: self.chats as [AnyObject])
})
}
ChatModel
public struct ChatModel: Codable {
// ... other properties
public var chatMessageId: String
enum CodingKeys: String, CodingKey {
// ... other cases
case chatMessageId = "message_id"
}
init (message:String , fromId:String, toID : String, imgUrl : URL?, chatMessageId : String) {
// ... other properties
self.chatMessageId = chatMessageId
}
}
// .... decoders etc
}
MessageModel
public struct MessageModel: Codable {
// ...
public var chatMessageId: String
enum CodingKeys: String, CodingKey {
// ... other cases
case chatMessageId = "message_id"
}
// ... init/decoders etc
}
Messages.json
[
{
"userid": "4444",
"nickname": "Marco",
"online_status": "offline",
"message": "Have you seen his dog?",
"city": "Madrid",
"flag_url": "https://i.imgur.com/PJcyle7.jpg",
"creationDate": "2016-02-22 15:18:40",
"avatar_url": "https://i.imgur.com/PJcyle7.jpg",
"message_id": "Tva9d2OJyWHRC1AqEfKjclRwXnlRDQ" // different id
},
{
"userid": "12121",
"nickname": "Tom",
"online_status": "online",
"message": "Where is the pizza shop?",
"city": "Kyoto",
"flag_url": "https://i.imgur.com/PJcyle7.jpg",
"creationDate": "2016-02-22 15:18:40",
"avatar_url": "https://i.imgur.com/PJcyle7.jpg",
"message_id": "EnotMkk8REEd0DHGvUgnd45wBap80E" // different id
}
]
Chats.json
2个对话,每个对话包含2条消息。每个对话都有一个独特的fromId
(伙伴),toID
(我自己)和独特的message_id
。
[
{
"fromId": "zz1234skjksmsjdfwe2zz",
"toId": "qq43922sdkfjsfmmxdfqq",
"messageText": "Have you seen is dog?",
"imageUrl": "https://i.imgur.com/PJcyle7.jpg",
"message_id": "Tva9d2OJyWHRC1AqEfKjclRwXnlRDQ", // conversation 1 - same message id as the 1st message in Messages.josn with nickname Marco.
"read": "true"
},
{
"fromId": "zz1234skjksmsjdfwe2zz",
"toId": "qq43922sdkfjsfmmxdfqq",
"messageText": "Yes I have. It's cute.",
"imageUrl": "https://i.imgur.com/PJcyle7.jpg",
"message_id": "Tva9d2OJyWHRC1AqEfKjclRwXnlRDQ", // conversation 1
"read": "true"
},
{
"fromId": "bb888skjaaasjdfwe2333",
"toId": "qq43922sdkfjsfmmxdfqq",
"messageText": "What kind of pizza do you want?",
"imageUrl": "https://i.imgur.com/PJcyle7.jpg",
"message_id": "EnotMkk8REEd0DHGvUgnd45wBap80E", // conversation 2 - same message id as the 2nd message in Messages.josn with nickname Tom.
"read": "true"
},
{
"fromId": "bb888skjaaasjdfwe2333",
"toId": "qq43922sdkfjsfmmxdfqq",
"messageText": "I like ham & pineapple pizza.",
"imageUrl": "https://i.imgur.com/PJcyle7.jpg",
"message_id": "EnotMkk8REEd0DHGvUgnd45wBap80E", // conversation 2
"read": "true"
}
]
let msg = try decoder.decode([ChatModel].self, from: data)
self.chats = msg
您将Chats.json
中包含的所有聊天数据存储到chats
属性中。
要过滤聊天,请尝试更换第二行,如下所示
self.chats = msg.filter { chat in
return chat.chatMessageId == self.messageModel.chatMessageId
}
或者,虽然我不知道为什么所有的聊天都包含在单个json文件中,但最好将json文件分成多个文件,例如Chat-Tva9d2OJyWHRC1AqEfKjclRwXnlRDQ.json
。
我希望这将有所帮助。
你的MessageListController didSelectRowAt
方法应该就这么简单。
//MessageListController
// ...code...
let messageObject = [MessageModel]()
// var chatObject = [ChatModel]()
// ...code...
override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) {
//creating a context with the message object at selected row.
var messageContext = messageObject[rowIndex]
// WatchKit's model presentation method. passing the context along.
presentController(withName: "ChatDetailController", context: messageContext)
// Rest of the codes not required in your MessageListController
}
// ...code...
你的MessageListController就是这样的。
// ChatDetailController
var chats: [ChatModel] = []
var messageModel: MessageModel? {
didSet {
guard let model = messageModel else { return }
partnerLabel.setText(model.nickname)
}
}
override func awake(withContext context: Any?) {
super.awake(withContext: context)
if let message = context as? MessageModel {
self.messageModel = message
print("Passed context: \(String(describing: messageModel))")
} else {
print("Passed context error: \(String(describing: context))")
}
do {
guard let fileUrl = Bundle.main.url(forResource: "Chats", withExtension: "json") else {
print("File could not be located")
return
}
let data = try Data(contentsOf: fileUrl)
let decoder = JSONDecoder()
//msg holds all chat messages in the file
let msg = try decoder.decode([ChatModel].self, from: data)
// We should filter the chats in the msg array with the selected message content
self.chats = msg.filter({
$0.chatMessageId == messageModel?.chatMessageId
})
// self.chats only holds the chats with chatMessageId
} catch let error {
print(error)
}
DispatchQueue.main.async(execute: {
self.setupTable(chatMessageArray: self.chats as [AnyObject])
})
希望这能解决您的问题。快乐编码:)