本文只记录一些关键点,初始配置查看官方文档:
TIMChat源码导读:https://cloud.tencent.com/document/product/269/3890
文档概述:https://cloud.tencent.com/document/product/269/9147gate.m :
iIM登录:(由于界面由h5编写,url为h5传值)
_loginParam = [[IMALoginParam alloc] init]; [IMAPlatform configWith:_loginParam.config]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ NSArray *params =[url.query componentsSeparatedByString:@"&"]; NSMutableDictionary *tempDic = [NSMutableDictionary dictionary]; for (NSString *paramStr in params) { NSArray *dicArray = [paramStr componentsSeparatedByString:@"="]; if (dicArray.count > 1) { NSString *decodeValue = [dicArray[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; [tempDic setObject:decodeValue forKey:dicArray[0]]; } } NSString *appid = [tempDic objectForKey:@"appid"]; NSString *identifier = [tempDic objectForKey:@"identifier"]; NSString *usersig = [tempDic objectForKey:@"usersig"]; _loginParam.identifier = identifier; _loginParam.userSig = usersig; _loginParam.tokenTime = [[NSDate date] timeIntervalSince1970]; //直接登录 __weak IMALoginController *weakSelf = self; [[HUDHelper sharedInstance] syncLoading:@"正在登录"]; [[IMAPlatform sharedInstance] login:_loginParam succ:^{ [[HUDHelper sharedInstance] syncStopLoadingMessage:@"登录成功"]; [weakSelf registNotification]; [weakSelf enterMainUI]; } fail:^(int code, NSString *msg) { [[HUDHelper sharedInstance] syncStopLoadingMessage:IMALocalizedError(code, msg) delay:2 completion:^{ [weakSelf loginWith:url]; }]; }]; });
//必须在登录之后上传token.在登录之后注册通知,保证通知回调也在登录之后,在通知的回调中上传的token。(回调在IMAAppDelegate的didRegisterForRemoteNotificationsWithDeviceToken中) - (void)registNotification { if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) { [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]]; [[UIApplication sharedApplication] registerForRemoteNotifications]; } else { [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)]; } }
IM登出:
[[HUDHelper sharedInstance] syncLoading:@"正在退出"]; [[IMAPlatform sharedInstance] logout:^{ [[HUDHelper sharedInstance] syncStopLoadingMessage:@"退出成功" delay:2 completion:^{ }]; NSLog(@"退出登录成功"); } fail:^(int code, NSString *err) { [[HUDHelper sharedInstance] syncStopLoadingMessage:IMALocalizedError(code, err) delay:2 completion:^{ }]; NSLog(@"退出登录失败: code=%d err=%@", code, err); }];
IM消息接收:需要注册新消息通知回调-><TIMMessageListener>
- (void)onNewMessage:(NSArray*) msgs { for (TIMMessage *msg in msgs) { int elemCount = [msg elemCount]; for (int i = 0; i < elemCount; i++) { TIMElem * elem = [msg getElem:i]; if ([elem isKindOfClass:[TIMTextElem class]]) { TIMTextElem * text_elem = (TIMTextElem * )elem; NSString *message = text_elem.text; [_delegate sendNewMsg:message]; }else if ([elem isKindOfClass:[TIMCustomElem class]]) { TIMCustomElem *elem = (TIMCustomElem *)[msg getElem:i]; NSString *message = [[NSString alloc] initWithData:elem.data encoding:NSUTF8StringEncoding]; [_delegate sendNewMsg:message]; } TIMAPNSConfig *config = [[TIMAPNSConfig alloc]init]; [config setOpenPush:1]; config.c2cSound = @"01.caf"; [config setGroupSound:@"00.caf"]; [config setVideoSound:@"11.caf"]; [[TIMManager sharedInstance] setAPNS:config succ:^{ NSLog(@"设置成功!"); } fail:^(int code, NSString *err){ NSLog(@"设置失败!"); }]; } } }
IM推送通知:
离线推送额外配置:https://cloud.tencent.com/document/product/269/9154
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{ // 处理推送消息 DebugLog(@"userinfo:%@",userInfo); DebugLog(@"收到推送消息:%@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]); } - (void)applicationWillEnterForeground:(UIApplication *)application { [[IMAPlatform sharedInstance] configOnAppEnterForeground]; } - (void)applicationDidEnterBackground:(UIApplication *)application { __block UIBackgroundTaskIdentifier bgTaskID; bgTaskID = [application beginBackgroundTaskWithExpirationHandler:^ { //不管有没有完成,结束background_task任务 [application endBackgroundTask: bgTaskID]; bgTaskID = UIBackgroundTaskInvalid; }]; }
// app 进入后台时配置 - (void)configOnAppEnterBackground:(NSInteger)readCount withUnReadCount:(NSInteger)unReadCount; { // 将相关的配置缓存至本地 [[IMAPlatform sharedInstance] saveToLocal]; NSInteger unReadCount_end = unReadCount-readCount; [UIApplication sharedApplication].applicationIconBadgeNumber = unReadCount_end; TIMBackgroundParam *param = [[TIMBackgroundParam alloc] init]; [[TIMManager sharedInstance] doBackground:param succ:^() { DebugLog(@"doBackgroud Succ"); } fail:^(int code, NSString * err) { DebugLog(@"Fail: %d->%@", code, err); }]; }
// app 进前台时配置 - (void)configOnAppEnterForeground { [UIApplication.sharedApplication.windows enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(UIWindow *w, NSUInteger idx, BOOL *stop) { if (!w.opaque && [NSStringFromClass(w.class) hasPrefix:@"UIText"]) { // The keyboard sometimes disables interaction. This brings it back to normal. BOOL wasHidden = w.hidden; w.hidden = YES; w.hidden = wasHidden; *stop = YES; } }]; //清空通知栏消息 [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 1]; [[UIApplication sharedApplication] cancelAllLocalNotifications]; [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; [[TIMManager sharedInstance] removeMessageListener:_conversationMgr]; _conversationMgr = nil; }
// app become active - (void)configOnAppDidBecomeActive { [[TIMManager sharedInstance] doForeground:^{ DebugLog(@"doForegroud Succ"); } fail:^(int code, NSString *msg) { DebugLog(@"Fail: %d->%@", code, msg); }]; } // app 注册APNS成功后 - (void)configOnAppRegistAPNSWithDeviceToken:(NSData *)deviceToken { DebugLog(@"didRegisterForRemoteNotificationsWithDeviceToken:%ld", (unsigned long)deviceToken.length); NSString *token = [NSString stringWithFormat:@"%@", deviceToken]; [[TIMManager sharedInstance] log:TIM_LOG_INFO tag:@"SetToken" msg:[NSString stringWithFormat:@"My Token is :%@", token]]; TIMTokenParam *param = [[TIMTokenParam alloc] init]; #if kAppStoreVersion // AppStore版本 #if DEBUG param.busiId = 8447; #else param.busiId = 8447; #endif #else //企业证书id param.busiId = 8448; #endif [param setToken:deviceToken]; // [[TIMManager sharedInstance] setToken:param]; [[TIMManager sharedInstance] setToken:param succ:^{ NSLog(@"-----> 上传token成功 "); } fail:^(int code, NSString *msg) { NSLog(@"-----> 上传token失败 "); }]; }