使用 XMPPFramework for ios 存储消息?

发布于 2024-12-22 09:46:56 字数 275 浏览 1 评论 0原文

我不确定如何使用 XMPPFramework 的核心数据来存储传入消息。有人有关于如何执行此操作的教程吗?我看到用户对象,它又可以拥有许多“资源”。收到的每条消息是否都应该是我创建并保留的新资源?

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

谢谢!

I'm not sure how to use the XMPPFramework's core data to store incoming messages. Does anyone have any tutorials on how to do this? I see User objects, which in turn can have many "resources". Is each message received supposed to be a new resource that I create and persist?

I do not know what part is my responsibility and what part the framework provides regarding message history. I can intercept every incoming message. Then am I supposed to create and store each message inside a Messages table using core data?
I'd have a Message Entity. And each XMPPUser would have an array of Message objects. But then wouldn't I be rolling my own solution, which would be working against the framework?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

似梦非梦 2024-12-29 09:46:56

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

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

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

以下一行代码使您无需将存档特定节发送到 xmpp 服务器
这很可能会以 service-not-implemented 来响应

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

希望它有帮助:)

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 :)

风吹雨成花 2024-12-29 09:46:56

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

The responses that indicate XMPP Framework doesn't save the history are incorrect.

To integrate results in a table view use:

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];
向日葵 2024-12-29 09:46:56

在 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 [email protected]


        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 = "[email protected]"
                    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
        }

    }

an example to get archived messages in Swift 4

declares and initializes the variables XMPPMessageArchivingCoreDataStorage where I initialize the 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)

doing this, whenever a message arrives, this will cause it to be archived without needing to do anything else.

then, to retrieve the archived message

func RecibedMessageArchiving(idFriend: String) {

        let JabberIDFriend = idFriend   //id friend chat, example [email protected]


        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 = "[email protected]"
                    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
        }

    }
遮云壑 2024-12-29 09:46:56

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

    }

}

当从表视图中选择特定用户时检索聊天历史记录...以下方法显示如何检索聊天历史记录...并从 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"]);
       }
     }


}

我希望这对您有用

XMPPFramework does not store message history,So i suggest to you it is better to use core data.Create a table by taking sender,receiver,message,time as columns .Insert record when send message method calling and receive message method calling...

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

    }

}

Retrive chat history when specific user selected from tableview.... the fallowing method shows how to retrive chat history...and call this method from didSelectRowAtIndexPath method and pass destination id as parameter

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


}

I hope this is useful to you

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文