28

我不确定如何使用 XMPPFramework 的核心数据来存储传入的消息。有没有人有任何关于如何做到这一点的教程?我看到用户对象,它又可以有很多“资源”。收到的每条消息都应该是我创建并保留的新资源吗?

我不知道我的职责是哪一部分,以及框架提供的有关消息历史的哪一部分。我可以拦截每条传入的消息。那么我应该使用核心数据在 Messages 表中创建和存储每条消息吗?我会有一个消息实体。每个 XMPPUser 都会有一个 Message 对象数组。但是,我不会推出我自己的解决方案,这将与框架相悖吗?

谢谢!

4

4 回答 4

52

I know this is an old thread but as I am currently working with XMPP on iOS I must say that there is a built in support for archiving messages in XMPP.

I downloaded the XMPP framework for iOS and in it there is folder marked XEP-0136. Import the folders in XCode and activate client side archiving by using the following lines of code in the class you instantiate XMPP client:

xmppMessageArchivingStorage = [XMPPMessageArchivingCoreDataStorage sharedInstance];
xmppMessageArchivingModule = [[XMPPMessageArchiving alloc] initWithMessageArchivingStorage:xmppMessageArchivingStorage];

the following one line of code saves you from sending archive specific stanzas to the xmpp server which will most probably respond with service-not-implemented

[xmppMessageArchivingModule setClientSideMessageArchivingOnly:YES];

[xmppMessageArchivingModule activate:xmppStream];
[xmppMessageArchivingModule  addDelegate:self delegateQueue:dispatch_get_main_queue()];

And you are set. From that moment on, messages (outgoing and incoming) will be stored in a table created by the framework.

If you need more info please comment and i will get back to you.

@PraviJay

I did like this :

-(void)testMessageArchiving{
            XMPPMessageArchivingCoreDataStorage *storage = [XMPPMessageArchivingCoreDataStorage sharedInstance];
            NSManagedObjectContext *moc = [storage mainThreadManagedObjectContext];
            NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"XMPPMessageArchiving_Message_CoreDataObject"
                                                                 inManagedObjectContext:moc];
            NSFetchRequest *request = [[NSFetchRequest alloc]init];
            [request setEntity:entityDescription];
            NSError *error;
            NSArray *messages = [moc executeFetchRequest:request error:&error];

            [self print:[[NSMutableArray alloc]initWithArray:messages]];
}

-(void)print:(NSMutableArray*)messages{
         @autoreleasepool {
            for (XMPPMessageArchiving_Message_CoreDataObject *message in messages) {
                NSLog(@"messageStr param is %@",message.messageStr);
                NSXMLElement *element = [[NSXMLElement alloc] initWithXMLString:message.messageStr error:nil];
                NSLog(@"to param is %@",[element attributeStringValueForName:@"to"]);
                NSLog(@"NSCore object id param is %@",message.objectID);
                NSLog(@"bareJid param is %@",message.bareJid);
                NSLog(@"bareJidStr param is %@",message.bareJidStr);
                NSLog(@"body param is %@",message.body);
                NSLog(@"timestamp param is %@",message.timestamp);
                NSLog(@"outgoing param is %d",[message.outgoing intValue]);
            }
        }
}

Hope it helps :)

于 2013-01-16T15:32:38.910 回答
10

指示 XMPP 框架不保存历史记录的响应不正确。

要将结果集成到表格视图中,请使用:

XMPPMessageArchivingCoreDataStorage *storage = [XMPPMessageArchivingCoreDataStorage sharedInstance];
NSManagedObjectContext *moc = [storage mainThreadManagedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"XMPPMessageArchiving_Contact_CoreDataObject"
                                                     inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entityDescription];

_contactsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:moc sectionNameKeyPath:nil cacheName:@"MessagesContactListCache"];

NSError *error;
BOOL rval = [_contactsController performFetch:&error];
于 2013-05-03T19:14:56.287 回答
0

在 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
        }

    }
于 2018-11-22T18:51:10.013 回答
-4

XMPPFramework不存储消息历史,所以我建议你最好使用核心数据。以发送者,接收者,消息,时间为列创建表。发送消息方法调用和接收消息方法调用时插入记录...

-(void)saveChatHistory:(NSString *)sender:(NSString*)receiver:(NSString*)message:(NSString*)time
{
    NSManagedObjectContext *context=[[self appDelegate] managedObjectContext];
    NSManagedObject *newContext=[NSEntityDescription insertNewObjectForEntityForName:@"ChatHistory" inManagedObjectContext:context];
    [newContext setValue:sender forKey:@"sender"];
    [newContext setValue:receiver forKey:@"receiver"];
    [newContext setValue:message forKey:@"message"];
    [newContext setValue:time forKey:@"time"];
    NSError *error;
    if(![context save:&error])
    {
        UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"Error Occured" message:@"Data is not Stored in Database Try Again" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
        [alertView show];

    }

}

当从 tableview 中选择特定用户时检索聊天历史....休闲方法显示如何检索聊天历史...并从 didSelectRowAtIndexPath 方法调用此方法并将目标 ID 作为参数传递

-(void)getChatHistory:(NSString*)jidString1
{


    NSManagedObjectContext *context=[[self appDelegate] managedObjectContext];
    NSEntityDescription *entity=[NSEntityDescription entityForName:@"ChatHistory" inManagedObjectContext:context];
    NSFetchRequest *req=[[NSFetchRequest alloc] init];

    NSPredicate *predicate=[NSPredicate predicateWithFormat:@"receiver=%@",jidString1];
    [req setEntity:entity];
    [req setPredicate:predicate];
    NSManagedObject *matchRecords=nil;
    NSError *error;
    NSArray *objects=[context executeFetchRequest:req error:&error];

    if([objects count]==0)
    {
        UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"No Record found" message:@"there is no previous chat history" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
        [alertView show];
    }
    else 
    {
        for(int i=0;i<[objects count];i++)
        {
         matchRecords=[objects objectAtIndex:i ];
         NSLog(@"sender is %@",[matchRecords valueForKey:@"sender"]);
         NSLog(@"reciver is %@",[matchRecords valueForKey:@"receiver"]);
         NSLog(@"messages is %@",[matchRecords valueForKey:@"message"]);
         NSLog(@"time is %@",[matchRecords valueForKey:@"time"]);
       }
     }


}

我希望这对你有用

于 2012-07-28T09:50:02.413 回答