项目中实现极光IM 获取消息 使用本地推送代码如下:
AppDelegate 注册本地通知
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
AppDelegate获取未读消息中 获取到消息
#pragma mark 获取未读消息
- (void)onReceiveMessage:(JMSGMessage *)message error:(NSError *)error{
int unread = [[JMSGConversation getAllUnreadCount] intValue];
NSDictionary *dict=[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%d",unread] forKey:@"content" ];
NSNotification *notification = [NSNotification notificationWithName:@"unread" object:self userInfo:dict];
#pragma mark 发送通知
[[NSNotificationCenter defaultCenter]postNotification:notification];
if (error == nil) {
dispatch_async(dispatch_get_main_queue(), ^{
if (@available(iOS 10.0, *)) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
// content.title = @"";
content.subtitle = message.fromName;
if (message.contentType == kJMSGContentTypeText) {
content.body = ((JMSGTextContent *)message.content).text;
}else if (message.contentType == kJMSGContentTypeImage){
content.body = @"[图片]";
}else if (message.contentType == kJMSGContentTypeVoice){
content.body = @"[语音]";
}else if (message.contentType == kJMSGContentTypePrompt){
if (message.content) {
NSString *str = ((JMSGPromptContent *)message.content).promptText;
if ([str containsString:@"撤回"]) {
content.body = [NSString stringWithFormat:@"%@ 撤回了一条消息",content.subtitle];
}else{
content.body = @"收到一条消息";
}
}
}else{
content.body = @"收到一条消息";
}
// 默认声音
content.sound = [UNNotificationSound defaultSound];
// 角标
int unread = [[JMSGConversation getAllUnreadCount] intValue];
if (unread>0) {
content.badge = [NSNumber numberWithInt:unread];
}else{
content.badge = @1;
}
// 多少秒后发送,可以将固定的日期转化为时间
NSTimeInterval time = [[NSDate dateWithTimeIntervalSinceNow:1] timeIntervalSinceNow];
// NSTimeInterval time = 10;
// repeats,是否重复,如果重复的话时间必须大于60s,要不会报错
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:time repeats:NO];
// 添加通知的标识符,可以用于移除,更新等操作
NSString *identifier = @"noticeId";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
[center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) {
// NSLog(@"成功添加推送");
}];
}else {
if (error.code==863004){
[self IMLogin];
}
}
});
}
}
效果图如下