//
// JXXMPP.m
// 草泥马农商银行
//
// Created by cerastes on 13-8-10.
// Copyright (c) 2014年 <span style="font-family: Arial, Helvetica, sans-serif;">cerastes</span><span style="font-family: Arial, Helvetica, sans-serif;">. All rights reserved.</span>
//
// 农商银行领导是傻逼
#import "JXXMPP.h"
#import "GCDAsyncSocket.h"
#import "XMPP.h"
#import "XMPPReconnect.h"
#import "XMPPCapabilities.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
#import "XMPPRoster.h"
#import "XMPPMessage.h"
#import "TURNSocket.h"
#import "SBJsonWriter.h"
#import "AppDelegate.h"
#import "FMDatabase.h"
//#import "emojiViewController.h"
#import "JXRoomPool.h"
#if DEBUG
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#else
static const int ddLogLevel = LOG_LEVEL_INFO;
#endif
#define DOCUMENT_PATH NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]
#define CACHES_PATH NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]
@implementation JXXMPP
@synthesize stream=xmppStream,isLogined,roomPool;
@synthesize friendsListDelegate;
static JXXMPP *sharedManager;
- (void)saveContext{
}
-(void)sendFile:(NSData*)aData toJID:(XMPPJID*)aJID{
}
+(JXXMPP*)sharedInstance{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedManager=[[JXXMPP alloc]init];
sharedManager.isLogined = NO;
[DDLog addLogger:[DDTTYLogger sharedInstance]];
// [[NSUserDefaults standardUserDefaults]setObject:[[NSUserDefaults standardUserDefaults]objectForKey:kMY_USER_ID] forKey:kXMPPmyJID];
// [[NSUserDefaults standardUserDefaults]setObject:[[NSUserDefaults standardUserDefaults]objectForKey:kMY_USER_PASSWORD] forKey:kXMPPmyPassword];
// [[NSUserDefaults standardUserDefaults]synchronize];
[sharedManager setupStream];
});
return sharedManager;
}
-(void)login{
if(isLogined)
return;
if (![self connect]) {
[g_App showAlert:@"连接失败"];
};
}
-(void)logout{
if(!isLogined)
return;
self.isLogined = NO;
[self disconnect];
[roomPool deleteAll];
[[NSNotificationCenter defaultCenter] postNotificationName:kLoginNotifaction object:[NSNumber numberWithBool:isLogined]];
}
- (void)dealloc
{
[_db close];
[_db release];
[self teardownStream];
[roomPool release];
[super dealloc];
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Saves changes in the application's managed object context before the application terminates.
}
#pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
#pragma mark ------收发消息-------
- (void)sendMessage:(JXMessageObject*)msg roomName:(NSString*)roomName{
//采用SBjson将params转化为json格式的字符串
// SBJsonWriter * OderJsonwriter = [SBJsonWriter new];
NSString * jsonString = msg.content;
// [OderJsonwriter release];
if(roomName == nil){
//点对点收发信息,两个人聊天
//[msg save]; //在回调里面做保存,消息有可能发送不成功,如何处理
}else{
//发送到聊天室
msg.isGroup = YES;
// [msg saveRoomMsg:roomName];
}
XMPPMessage *aMessage = nil;
if(roomName == nil){
aMessage=[XMPPMessage messageWithType:@"chat" to:[XMPPJID jidWithString:[NSString stringWithFormat:@"%@@%@",msg.toUserId,kXMPP_Domain]] elementID:msg.messageId];
}else{
NSString* roomJid = [NSString stringWithFormat:@"%@@conference.%@",roomName,kXMPP_Domain];
aMessage=[XMPPMessage messageWithType:@"groupchat" to:[XMPPJID jidWithString:roomJid] elementID:msg.messageId];
}
[aMessage addChild:[DDXMLNode elementWithName:@"body" stringValue:jsonString]];
DDXMLElement *request = [DDXMLElement elementWithName:@"request" xmlns:@"urn:xmpp:receipts"];
[aMessage addChild:request];
[xmppStream sendElement:aMessage];
}
-(void)sendElement:(NSXMLElement *)message{
[xmppStream sendElement:message];
}
#pragma mark --------配置XML流---------
- (void)setupStream
{
NSAssert(xmppStream == nil, @"Method setupStream invoked multiple times");
xmppStream = [[XMPPStream alloc] init];
#if !TARGET_IPHONE_SIMULATOR
{
xmppStream.enableBackgroundingOnSocket = YES;
}
#endif
xmppReconnect = [[XMPPReconnect alloc] init];
xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] init];
xmppRoster = [[XMPPRoster alloc] initWithRosterStorage:xmppRosterStorage];
xmppRoster.autoFetchRoster = YES;
xmppRoster.autoAcceptKnownPresenceSubscriptionRequests = YES;
[xmppReconnect activate:xmppStream];
[xmppRoster activate:xmppStream];
// Add ourself as a delegate to anything we may be interested in
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
[xmppStream setHostName:kXMPPHost];
[xmppStream setHostPort:5222];
// You may need to alter these settings depending on the server you're connecting to
allowSelfSignedCertificates = NO;
allowSSLHostNameMismatch = NO;
self.isLogined = NO;
self.roomPool = [[[JXRoomPool alloc] init] autorelease];
}
- (void)teardownStream
{
[xmppStream removeDelegate:self];
[xmppReconnect deactivate];
[xmppStream disconnect];
xmppStream = nil;
xmppReconnect = nil;
}
// It's easy to create XML elments to send and to read received XML elements.
// You have the entire NSXMLElement and NSXMLNode API's.
//
// In addition to this, the NSXMLElement+XMPP category provides some very handy methods for working with XMPP.
//
// On the iPhone, Apple chose not to include the full NSXML suite.
// No problem - we use the KissXML library as a drop in replacement.
//
// For more information on working with XML elements, see the Wiki article:
// http://code.google.com/p/xmppframework/wiki/WorkingWithElements
- (void)goOnline{
XMPPPresence *presence = [XMPPPresence presence]; // type="available" is implicit
[xmppStream sendElement:presence];
}
- (void)goOffline{
XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
[xmppStream sendElement:presence];
}
#pragma mark Connect/disconnect
- (BOOL)connect{
if (![xmppStream isDisconnected]) {
return YES;
}
NSString *myJID = [[NSUserDefaults standardUserDefaults] stringForKey:IMDeviceCodeForLogin];
NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:kMY_USER_PASSWORD];
if (myJID == nil || myPassword == nil) {
return NO;
}
[xmppStream setMyJID:[XMPPJID jidWithUser:myJID domain:kXMPP_Domain resource:@"Android"]];
password=myPassword;
NSError *error = nil;
if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error]){
[g_App showAlert:[NSString stringWithFormat:@"连接出错:%@",error.localizedDescription]];
DDLogError(@"Error connecting: %@", error);
return NO;
}
return YES;
}
- (void)disconnect{
[self goOffline];
[xmppStream disconnect];
}
#pragma mark UIApplicationDelegate
- (void)applicationDidEnterBackground:(UIApplication *)application{
// Use this method to release shared resources, save user data, invalidate timers, and store
// enough application state information to restore your application to its current state in case
// it is terminated later.
//
// If your application supports background execution,
// called instead of applicationWillTerminate: when the user quits.
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
#if TARGET_IPHONE_SIMULATOR
DDLogError(@"The iPhone simulator does not process background network traffic. "
@"Inbound traffic is queued until the keepAliveTimeout:handler: fires.");
#endif
if ([application respondsToSelector:@selector(setKeepAliveTimeout:handler:)]){
[application setKeepAliveTimeout:600 handler:^{
DDLogVerbose(@"KeepAliveHandler");
// Do other keep alive stuff here.
}];
}
}
- (void)applicationWillEnterForeground:(UIApplication *)application{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (NSManagedObjectContext *)managedObjectContext_roster{
return [xmppRosterStorage mainThreadManagedObjectContext];
}
// Returns the URL to the application's Documents directory.
#pragma mark XMPPStream Delegate
- (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket{
// DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
if (allowSelfSignedCertificates)
{
[settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];
}
if (allowSSLHostNameMismatch)
{
[settings setObject:[NSNull null] forKey:(NSString *)kCFStreamSSLPeerName];
}
else
{
// Google does things incorrectly (does not conform to RFC).
// Because so many people ask questions about this (assume xmpp framework is broken),
// I've explicitly added code that shows how other xmpp clients "do the right thing"
// when connecting to a google server (gmail, or google apps for domains).
NSString *expectedCertName = nil;
NSString *serverDomain = xmppStream.hostName;
NSString *virtualDomain = [xmppStream.myJID domain];
if ([serverDomain isEqualToString:@"talk.google.com"])
{
if ([virtualDomain isEqualToString:@"gmail.com"])
{
expectedCertName = virtualDomain;
}
else
{
expectedCertName = serverDomain;
}
}
else if (serverDomain == nil)
{
expectedCertName = virtualDomain;
}
else
{
expectedCertName = serverDomain;
}
if (expectedCertName)
{
[settings setObject:expectedCertName forKey:(NSString *)kCFStreamSSLPeerName];
}
}
}
- (void)xmppStreamDidSecure:(XMPPStream *)sender{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStreamDidConnect:(XMPPStream *)sender{
// DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
//连接建立成功,然后
isXmppConnected = YES;
NSError *error = nil;
if(![xmppStream authenticateWithPassword:password error:&error]){
//DDLogError(@"Error authenticating: %@", error);
}
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender{
NSLog(@"认证通过,上线了");
//DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
[self goOnline];
// [xmppRoster fetchRoster]; //获取好友列表,通过协议中定义的方法,获取好友列表
self.isLogined = YES; //授权成功后,更新登录状态,用户已经登录成功
//[self.roomPool createAll]; //登录成功后,从本地化的信息中创建,所有的聊天室
//发送通知,用户的登陆状态发生改变了
// [[NSNotificationCenter defaultCenter] postNotificationName:kLoginNotifaction object:[NSNumber numberWithBool:isLogined]];
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error{
// DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
//1 心跳包,会在这里接受到,然后xmpp自动发回一个报文
//2 好友列表在这里
//<iq type="result" to="im.srcb.com" id="723-8231" from="lujs2234@im.srcb.com/Android"/>
- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq{
//DDLogVerbose(@"%@: %@ - %@", THIS_FILE, THIS_METHOD, [iq elementID]);
// NSLog(@":%@",iq);
//iq 报文有四种类型(type) 1 set 写数据 2 get 请求数据 3 result,请求数据的返回结果 4 error
[self OCObjFromIQ:iq];
return NO;
}
-(void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message{
[self didReceiveMessage:message];
}
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence{
//上线状态,在此处回去jid
XMPPJID *fromJid = [presence from];
XMPPJID *toJid = [presence to];
NSDictionary * dic = [[[NSDictionary alloc]initWithObjectsAndKeys:fromJid.user,@"user",presence.priority,@"priority", nil] autorelease];
[[NSNotificationCenter defaultCenter] postNotificationName:@"stateChanged" object:dic];
//DDLogVerbose(@"%@: %@ - %@", THIS_FILE, THIS_METHOD, [presence fromStr]);
}
- (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error{
//DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error{
//DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
if (!isXmppConnected){
// DDLogError(@"Unable to connect to server. Check xmppStream.hostName");
}
}
#pragma mark XMPPRosterDelegate
- (void)xmppRoster:(XMPPRoster *)sender didReceivePresenceSubscriptionRequest:(XMPPPresence *)presence{
XMPPJID *jid=[XMPPJID jidWithString:[presence stringValue]];
[xmppRoster acceptPresenceSubscriptionRequestFrom:jid andAddToRoster:YES];
}
- (void)addSomeBody:(NSString *)userId{
[xmppRoster subscribePresenceToUser:[XMPPJID jidWithString:[NSString stringWithFormat:@"%@@%@",userId,kXMPP_Domain]]];
}
-(void)fetchUser:(NSString*)userId{
/*
ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:API_BASE_URL(@"user/get")];
[request setPostValue:userId forKey:@"userId"];
[request setDelegate:self];
[request setDidFinishSelector:@selector(requestSuccess:)];
[request setDidFailSelector:@selector(requestError:)];
[request startAsynchronous];
*/
}
/*
-(void)requestSuccess:(ASIFormDataRequest*)request
{
NSLog(@"response:%@",request.responseString);
SBJsonParser *paser=[[[SBJsonParser alloc]init]autorelease];
NSDictionary *rootDic=[paser objectWithString:request.responseString];
int resultCode=[[rootDic objectForKey:@"resultCode"]intValue];
if (resultCode==1) {
NSDictionary *dic=[rootDic objectForKey:@"data"];
if(dic){
JXUserObject *user=[JXUserObject userFromDictionary:dic];
[JXUserObject saveNewUser:user];
}
}
}
-(void)requestError:(ASIFormDataRequest*)request
{
}
*/
- (void)xmppStream:(XMPPStream *)sender didSendMessage:(XMPPMessage *)message{
NSString *body = [[message elementForName:@"body"] stringValue];
[self messageDidSend:message];
}
- (FMDatabase*)openUserDb:(NSString*)userId{
userId = [userId uppercaseString];
if([_userIdOld isEqualToString:userId]){
if(_db && [_db goodConnection])
return _db;
}
_userIdOld = [userId copy];
NSString* t = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString* s = [NSString stringWithFormat:@"%@/%@.db",t,userId];
[_db close];
[_db release];
_db = [[FMDatabase alloc] initWithPath:s];
if (![_db open]) {
NSLog(@"数据库打开失败");
return nil;
};
return _db;
}
#pragma mark- lekerning methods-------------------------
-(void)prepareFriendsData:(NSArray *)mData{
NSMutableArray *friends = [NSMutableArray arrayWithCapacity:2];
for(NSXMLElement *item in mData){
NSMutableDictionary *friend = [NSMutableDictionary dictionaryWithCapacity:2];
NSLog(@"item = %@",item);
NSString *jid = [item attributeStringValueForName:@"jid"];
NSArray *jidArray = [jid componentsSeparatedByString:@"@"];
NSString *name = [item attributeStringValueForName:@"name"];
NSString *subscription = [item attributeStringValueForName:@"subscription"];
NSString *groupElement = [[item elementForName:@"group"] stringValue];
if(jid){
[friend setObject:jidArray[0] forKey:@"jid"];
}
if(name){
[friend setObject:name forKey:@"name"];
}else{
[friend setObject:jidArray[0] forKey:@"name"]; //没有昵称,显示jid
}
if(subscription){
[friend setObject:subscription forKey:@"subscription"];
}
if (groupElement && (NSNull *)groupElement != [NSNull null]) {
[friend setObject:groupElement forKey:@"group"];
}
else
{
[friend setObject:@"未知分组" forKey:@"group"];
}
[friend setObject:@"1" forKey:@"statue"];
[friends addObject:friend];
}
NSLog(@"friends :%@",friends);
//此处保存好友列表,用于本地查询
[[NSUserDefaults standardUserDefaults] setObject:friends forKey:[NSString stringWithFormat:@"%@%@",KUserFriendsPrefix,TheLoginJID]];
if([self.friendsListDelegate respondsToSelector:@selector(friendsUpdate:)]){
[self.friendsListDelegate friendsUpdate:friends];
// 68813005
}
}
-(void)getFriendList{
[xmppRoster fetchRoster];
}
-(void)OCObjFromIQ:(XMPPIQ *)iq{
if([iq isErrorIQ]){
//最近联系人
NSXMLElement *query = iq.childElement;
NSString *iqAttribute = [iq xmlns];
NSString *ids = [iq attributeStringValueForName:@"id"];
if ([iqAttribute isEqualToString:@"jabber:client"] && ids && [ids rangeOfString:@"UsusllyChatFriends"].location != NSNotFound){
NSArray *items = [[[NSArray alloc] initWithArray:[query children]] autorelease];
NSMutableArray *friends = [NSMutableArray arrayWithCapacity:2];
for(NSXMLElement *item in items){
NSMutableDictionary *friend = [NSMutableDictionary dictionaryWithCapacity:2];
NSString *username = [[item elementForName:@"username"] stringValue]?[[item elementForName:@"username"] stringValue]:@"";
NSString *nickname = [[item elementForName:@"nickname"] stringValue]?[[item elementForName:@"nickname"] stringValue]:@"";
NSString *storeName = [[item elementForName:@"storeName"] stringValue]?[[item elementForName:@"storeName"] stringValue]:@"";
[friend setObject:username forKey:@"jid"];
[friend setObject:nickname forKey:@"name"];
[friend setObject:storeName forKey:@"storeName"];
[friend setObject:@"最近联系人" forKey:@"group"];
[friend setObject:@"1" forKey:@"statue"];
[friends addObject:friend];
}
[[NSNotificationCenter defaultCenter] postNotificationName:@"UsusllyChatFriends" object:friends];
}
}
if([iq isResultIQ]){
NSXMLElement *query = iq.childElement;
NSString *queryAttribute = [query xmlns];
// NSString *iqAttribute = [iq xmlns];
// NSLog(@"iq = %@ ids = %@",iq,ids);
if([queryAttribute isEqualToString:@"jabber:iq:roster"]){
//好友列表,保存
NSArray *toArray = [iq.toStr componentsSeparatedByString:@"@"];
if([toArray count] > 0){
//保存用户的jid,
NSLog(@"jid :%@",[toArray firstObject]);
[[NSUserDefaults standardUserDefaults] setObject:[toArray firstObject] forKey:kMY_USER_ID];
[[NSUserDefaults standardUserDefaults] synchronize];
}
NSArray *items = [[[NSArray alloc] initWithArray:[query children]] autorelease];
[self prepareFriendsData:items];
}
else if([queryAttribute isEqualToString:@"jabber:iq:private"]){
//群组列表,解析,转发,更新界面-
NSLog(@"收到群组列表 %@",iq);
NSXMLElement *query = iq.childElement;
NSArray *items = [[[NSArray alloc] initWithArray:[query children]] autorelease];
NSXMLElement *storage = [items objectAtIndex:0];
NSArray *conference = [[[NSArray alloc] initWithArray:[storage children]] autorelease];
NSMutableArray *groups = [NSMutableArray arrayWithCapacity:2];
for(NSXMLElement *item in conference){
NSMutableDictionary *group = [NSMutableDictionary dictionaryWithCapacity:2];
NSString *autojoin = [[item attributeForName:@"autojoin"] stringValue];
NSString *jid = [[[[item attributeForName:@"jid"] stringValue] componentsSeparatedByString:@"@"] objectAtIndex:0];
NSString *name = [[item attributeForName:@"name"] stringValue];
[group setObject:name forKey:@"name"];
[group setObject:jid forKey:@"jid"];
[group setObject:autojoin forKey:@"autojoin"];
[group setObject:@"群组" forKey:@"group"];
[group setObject:@"0" forKey:@"statue"];
[groups addObject:group];
}
NSLog(@"groups = %@",groups);
[[NSNotificationCenter defaultCenter] postNotificationName:@"groups" object:groups];
}
}
}
#pragma mark- message handle----
-(void)messageDidSend:(XMPPMessage *)message{
NSString *type = [[message attributeForName:@"type"] stringValue];
if([type isEqualToString:@"groupchat"]){
return;
}
NSString *body = [[message elementForName:@"body"] stringValue];
NSString *to = [[message to] bare];
NSArray *toCompents = [to componentsSeparatedByString:@"@"];
NSString *myJid = [[NSUserDefaults standardUserDefaults]objectForKey:kMY_USER_ID];
NSString *msgID = [[message attributeForName:@"id"] stringValue];
//创建一个消息对象,
JXMessageObject *msg=[[JXMessageObject alloc] init];
if([type isEqualToString:@"chat"] || [type isEqualToString:@"groupchat"]){
[msg setFromUserId:myJid];
if(msg.type != nil ){
if([type isEqualToString:@"chat"]){
NSMutableDictionary *msgDic = [NSMutableDictionary dictionaryWithCapacity:2];
[msgDic setObject:myJid forKey:kMESSAGE_FROM];
[msgDic setObject:toCompents[0] forKey:kMESSAGE_TO];
[msgDic setObject:@"0" forKey:kMESSAGE_ISREAD]; //默认未读
[msgDic setObject:body forKey:kMESSAGE_CONTENT];
NSDate *msgDate = [NSDate date];
// NSString *dateStr = [QuitTools stringFromDate:msgDate withFormate:@"yyyyMMdd HH:mm:ss"];
[msgDic setObject:msgDate forKey:kMESSAGE_DATE];
[msgDic setObject:msgID forKey:kMESSAGE_ID];
[msg fromDictionary:msgDic];
[[NSNotificationCenter defaultCenter] postNotificationName:KIMessageSendSuccessNote object:msg userInfo:nil];
}else{
/*
//处理聊天室,消息
msg.isGroup = YES;
NSString* room = [[message attributeForName:@"from"] stringValue];
NSRange range = [room rangeOfString:@"@"];
if(range.location != NSNotFound)
room = [room substringToIndex:range.location];
[msg saveRoomMsg:room];
*/
}
}
}
//发送通知 ,通知数据库更新了
[[NSNotificationCenter defaultCenter] postNotificationName:KIMSGControllerNeedUpdateNote object:nil];
[msg release];
}
-(void)didReceiveMessage:(XMPPMessage *)message{
NSString *delay = [[message elementForName:@"delay"] stringValue];
NSString* type = [[message attributeForName:@"type"] stringValue];
if(delay != nil && [type isEqualToString:@"groupchat"])//如果有延时,同时为群组聊天,返回,不作处理
return;
NSString *body = [[message elementForName:@"body"] stringValue];
NSString *from = [[message from] bare];
NSArray *fromCompents =[from componentsSeparatedByString:@"@"];
NSString *to = [[message to] bare];
NSArray *toCompents = [to componentsSeparatedByString:@"@"];
NSString *msgID = [[message attributeForName:@"id"] stringValue];//收到包里面都是有id的
JXMessageObject *msg=[[JXMessageObject alloc] init];
if([type isEqualToString:@"chat"] || [type isEqualToString:@"groupchat"]){
[msg setFromUserId:fromCompents[0]];
if(msg.type != nil ){
if([type isEqualToString:@"chat"]){
NSMutableDictionary *msgDic = [NSMutableDictionary dictionaryWithCapacity:2];
[msgDic setObject:fromCompents[0] forKey:kMESSAGE_FROM];
[msgDic setObject:toCompents[0] forKey:kMESSAGE_TO];
[msgDic setObject:[NSNumber numberWithBool:YES] forKey:kMESSAGE_ISSEND]; //默认未读
[msgDic setObject:[NSNumber numberWithBool:NO] forKey:kMESSAGE_ISREAD];
[msgDic setObject:body forKey:kMESSAGE_CONTENT];
NSDate *msgDate = [NSDate date];
[msgDic setObject:msgDate forKey:kMESSAGE_DATE];
[msgDic setObject:msgID forKey:kMESSAGE_ID]; //收到消息
[msg fromDictionary:msgDic];
[msg save]; //收到消息, 直接保存,发送接受请求
[[NSNotificationCenter defaultCenter] postNotificationName:KIMessageDidReceiveNote object:msg userInfo:nil];
}else{
/*
msg.isGroup = YES;
NSString* room = [[message attributeForName:@"from"] stringValue];
NSRange range = [room rangeOfString:@"@"];
if(range.location != NSNotFound)
room = [room substringToIndex:range.location];
[msg saveRoomMsg:room];
*/
}
}
}
//发送通知 ,通知数据库更新了
[[NSNotificationCenter defaultCenter] postNotificationName:KIMSGControllerNeedUpdateNote object:nil];
[msg release];
}
@end
xmpp解析
最新推荐文章于 2017-04-08 16:13:17 发布