通常使用MSMessage对象设置,我将使用MSMessageTemplateLayout作为发送MSMessage对象的基本设置。在iMessage API中,有一段有趣的代码,允许交互式MSMessage称为MSMessageLiveLayout,使用户无需完全打开MSMessage对象即可与MSMessage对象进行交互。
对于一个演示,我试图创建一个简单的计数器。对于MSMessage对象,我知道正确保存值更改的唯一方法是通过URL方案。
问题是我不确定如何正确更新当前的MSMessage URL以匹配新更改的值。另外,我将如何更新MSMessage对象的接收者端UI /数据以匹配发送者的变化?
每次按计数器按钮时,我试图通过使用新的URL值更新当前的activeConversation URL来访问当前的MSMessage URL。打印语句显示URL更新。但是,当我上下滚动MSMessage对象时,将调用willBecomeActive函数-放弃所有更改并继续使用旧的URL值。
class Demo: MSMessagesAppViewController {
var session: MSSession?
var count = 1
@IBOutlet var label: UILabel!
func createURL() -> URL {
var urlComponents = URLComponents()
urlComponents.scheme = "https";
urlComponents.host = "www.democounter.com";
let item = URLQueryItem(name: "counter", value: "\(count)")
urlComponents.queryItems?.append(item)
return urlComponents.url!
}
func createMessage(_ url: URL) {
if session == nil {
session = MSSession()
}
let message = MSMessage(session: session!)
let layout = MSMessageTemplateLayout()
layout.caption = "Sending counter"
let liveLayout = MSMessageLiveLayout(alternateLayout: layout)
message.layout = liveLayout
message.url = url
let conversation = self.activeConversation
conversation?.insert(message, completionHandler: {(error) in
if let error = error {
print(error)
}
})
self.dismiss()
}
// this is the blue box in the example attached that create and sends
the MSMessage object
@IBAction func sendMessage(_ sender: UIButton) {
let url = createURL()
createMessage(url)
}
// counter button, this is where I try to update the current MSMessage URL
@IBAction func PressMe(_ sender: UIButton) {
count += 1
print(count)
label.text = String(count)
let conversation = self.activeConversation
print(conversation?.selectedMessage?.url)
// It prints the changes, but does not save the updated url to
the current MSMessage Object
conversation?.selectedMessage?.url = createURL()
print(conversation?.selectedMessage?.url)
}
func decodeURL(_ url: URL) {
let components = URLComponents(url: url,
resolvingAgainstBaseURL: false)
for (index, queryItem) in (components?.queryItems?.enumerated())! {
if queryItem.name == "counter" {
count = Int(queryItem.value!)!
}
}
}
override func willBecomeActive(with conversation: MSConversation) {
if let messageURL = conversation.selectedMessage?.url {
decodeURL(messageURL)
caption = "It's your turn to counter"
session = conversation.selectedMessage?.session
}
label.text = String(count)
}
}
[消息对象示例](https://imgur.com/MVQipca)