在 Swift 4 中获取归档消息的示例
声明并初始化变量 XMPPMessageArchivingCoreDataStorage 我在其中初始化 XMPPStream
var xmppMessageStorage: XMPPMessageArchivingCoreDataStorage?
var xmppMessageArchiving: XMPPMessageArchiving?
xmppMessageStorage = XMPPMessageArchivingCoreDataStorage.sharedInstance()
xmppMessageArchiving = XMPPMessageArchiving(messageArchivingStorage: xmppMessageStorage)
xmppMessageArchiving?.clientSideMessageArchivingOnly = true
xmppMessageArchiving?.activate(stream)
xmppMessageArchiving?.addDelegate(self, delegateQueue: DispatchQueue.main)
这样做,每当消息到达时,这将导致它被归档而无需执行任何其他操作。
然后,检索归档的消息
func RecibedMessageArchiving(idFriend: String) {
let JabberIDFriend = idFriend //id friend chat, example test1@example.com
let moc = xmppMessageStorage?.mainThreadManagedObjectContext
let entityDescription = NSEntityDescription.entity(forEntityName: "XMPPMessageArchiving_Message_CoreDataObject", in: moc!)
let request = NSFetchRequest<NSFetchRequestResult>()
let predicateFormat = "bareJidStr like %@ "
let predicate = NSPredicate(format: predicateFormat, JabberIDFriend)
request.predicate = predicate
request.entity = entityDescription
//jabberID id del usuario, cliente
var jabberIDCliente = ""
if let jabberj = globalChat.value(forKey: "jabberID"){
jabberIDCliente = jabberj as! String
}
do {
let results = try moc?.fetch(request)
for message: XMPPMessageArchiving_Message_CoreDataObject? in results as? [XMPPMessageArchiving_Message_CoreDataObject?] ?? [] {
var element: DDXMLElement!
do {
element = try DDXMLElement(xmlString: (message as AnyObject).messageStr)
} catch _ {
element = nil
}
let body: String
let sender: String
let date: NSDate
let isIncomings: Bool
if message?.body != nil {
body = (message?.body)!
} else {
body = ""
}
if element.attributeStringValue(forName: "to") == JabberIDFriend {
sender = jabberIDCliente
isIncomings = false
} else {
sender = "test2@example.com"
isIncomings = true
}
var m: [AnyHashable : Any] = [:]
m["msg"] = message?.body
print("body", message?.body)
print("test", element.attributeStringValue(forName: "to"))
print("test2", element.attributeStringValue(forName: "body"))
}
} catch _ {
//catch fetch error here
}
}