根据选定的indexPath加载特定的json message_ids

时间:2019-04-14 03:28:45

标签: swift watchkit

目标:
当我从MessageListControllerdidSelectRowAt的聊天消息列表中选择一条消息时,我希望下一个ChatDetailController中打开的聊天会话与所选的相同会话匹配。明显。

我正在使用WatchKit,但是在此iOS图像中是同一回事。选择与Sophia的消息,并打开与Sophia的聊天。 enter image description here
我想传递json的“ message_id”,即模型中的chatMessageId属性。我已经在chatMessageId行中将MessageModelChatDetailController传递到presentController(withName: "ChatDetailController", context: messageContext)

这里是使用messageContext传递的数据的打印件。

  

传递的上下文:可选(HTWatch_Extension.MessageModel(合作伙伴:“ 9859”,昵称:“马可”,消息:“您看到过狗吗?”,城市:“ Madrid”,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"
  }
]

2 个答案:

答案 0 :(得分:4)

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文件中,但最好将Chat-Tva9d2OJyWHRC1AqEfKjclRwXnlRDQ.json之类的每次聊天将json文件分为多个文件。

我希望这会有所帮助。

答案 1 :(得分:1)

您的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])
        })

希望这可以解决您的问题。快乐编码:)