使用XMPPFramework为ios存储消息?

时间:2011-12-19 23:24:59

标签: iphone ios core-data storage xmppframework

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

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

谢谢!

4 个答案:

答案 0 :(得分:51)

我知道这是一个旧线程,但由于我目前正在使用iOS上的XMPP,我必须说有一个内置支持在XMPP中归档消息。

我下载了适用于iOS的XMPP框架,其中有一个标记为XEP-0136的文件夹。通过在实例化XMPP客户端的类中使用以下代码行来导入XCode中的文件夹并激活客户端存档:

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

以下一行代码可以避免将存档特定节发送到xmpp服务器 这很可能会响应服务未实现

[xmppMessageArchivingModule setClientSideMessageArchivingOnly:YES];

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

你已经定下来了。从那一刻起,消息(传出和传入)将存储在框架创建的表中。

如果您需要更多信息,请发表评论,我会回复您。

@PraviJay

我确实喜欢这个:

-(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]);
            }
        }
}

希望有所帮助:)

答案 1 :(得分:10)

表示XMPP Framework未保存历史记录的响应不正确。

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

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];

答案 2 :(得分: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
        }

    }

答案 3 :(得分:-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"]);
       }
     }


}

我希望这对你有用