Implementation of iOS Communication Notifications

background

Insert image description here
I saw some students in the group asking how to customize the icon on the left side of push notifications. Since iOS 10 has launched notification extensions, everyone knows that you can add media resources to notifications, such as pictures, audio and video, Notification Extensionetc. But we also know that the pictures added through the notification extension are displayed on the right side, as shown below:
Insert image description here
So how to modify the icon on the left side to achieve the effect of Apple SMS? We looked down with doubt.

plan

Communication Notifications

Searching Apple's official documents and WWDC 2021 found that after iOS 15, Apple launched a 通讯通知feature called. You can check out Apple’s official definition.

Apple has added the ability to distinguish your app’s notifications as communication notifications. These notifications will now feature the image or avatar of the contact they were sent from and can integrate with SiriKit so that Siri can intelligently provide shortcuts and suggestions for communication actions based on common contacts. For example, when users are setting allowed contacts for a Focus mode or are placing a call from your app. Siri will intelligently suggest contacts based on the intent data donated by your application.

Apple has added the ability to differentiate an app's notifications into communication notifications. These notifications will now include an image or avatar of the contact who sent them, and can be integrated with SiriKit so that Siri can intelligently provide shortcuts and suggestions for communication actions based on frequently used contacts. For example, when a user sets allowed contacts for Focus mode or makes a call from your application. Siri will intelligently suggest contacts based on intent data provided by your app.

That is to say, Apple provides the function of distinguishing push notifications into communication notifications, and communication notifications can display the user's avatar and other content.
Legend:
Insert image description here
After reading the definition and effects, we found that this is exactly the function we need, so how to implement it?

Communication Notifications specific implementation

To use communication notifications, apps will need to add the Communication Notifications capability to their App in Xcode and update the content of their notification in the app’s Notification Service Extension with an intent object that implements the new UNNotificationContentProviding protocol.

To use communication notifications, the APP needs to add the communication notification function to its APP in Xcode and implement the UNNotificationContentProviding protocol in the application notification service extension .

1. First add the following key values ​​to the APP Info.plist file
<key>NSUserActivityTypes</key>
   <array>
   	<string>INStartCallIntent</string>
   	<string>INSendMessageIntent</string>
   </array>

Insert image description here

2. Add function in Xcode-Signing & CapabilitiesCommunication Notifications

Insert image description here

Local notifications - implement communication notifications
1. First import the following header files
#import <Intents/Intents.h>
#import <UserNotifications/UserNotifications.h>
2. Create conversation information by using INPerson and INSendMessageIntent and add it to the APP’s push notification message.
//创建一个名字
NSPersonNameComponents *nameComponents = [[NSPersonNameComponents alloc] init];
nameComponents.nickname = message.fromUsername;// 用户名
//创建参与SiriKit交互的用户消息发送者   
INPerson *messageSender = [[INPerson alloc]initWithPersonHandle:[[INPersonHandle alloc]initWithValue:nil type:INPersonHandleTypeUnknown] nameComponents:nameComponents displayName:message.fromName image:avatarImage contactIdentifier:nil customIdentifier:message.fromUsername isMe:NO suggestionType:(INPersonSuggestionTypeNone)];
//创建发送消息请求    
INSendMessageIntent *intent = [[INSendMessageIntent alloc] initWithRecipients:@[messageSender] outgoingMessageType:(INOutgoingMessageTypeOutgoingMessageText) content:contentAttribut.string speakableGroupName:[[INSpeakableString alloc]initWithSpokenPhrase:@""] conversationIdentifier:message.msgId serviceName:nil sender:messageSender attachments:nil];
    
[intent setImage:avatarImage forParameterNamed:@"speakableGroupName"];

//创建SiriKit 交互对象    
INInteraction *interaction = [[INInteraction alloc]initWithIntent:intent response:nil];
interaction.direction = INInteractionDirectionIncoming;
[interaction donateInteractionWithCompletion:nil];

The complete implementation code is as follows:

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        content.title = message.fromName;
        content.body = contentAttribut.string;
        content.sound = [UNNotificationSound defaultSound];
        content.badge = @([UIApplication sharedApplication].applicationIconBadgeNumber + 1);
        content.userInfo = @{
    
    
            @"url":@"xxxxxxx",
        };
        if (@available(iOS 15.0, *)) {
    
    
            //实现私信消息内容展示
            if (message.fromUsername && message.fromAvatar && message.fromName && message.msgId)
            {
    
    
                //需要先将图片下载下来,我们这里使用的SDWebImageDownloader下载图片
                NSURL *imageURL = [NSURL URLWithString:message.fromAvatar];
                __block INImage *avatarImage = nil;
                
                [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:imageURL completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
    
    
                    if (image) {
    
    
                        avatarImage = [INImage imageWithImageData:data];
                    }
                    // 消息发送方
                    NSPersonNameComponents *nameComponents = [[NSPersonNameComponents alloc] init];
                    nameComponents.nickname = message.fromUsername;// 用户名

                    INPerson *messageSender = [[INPerson alloc]initWithPersonHandle:[[INPersonHandle alloc]initWithValue:nil type:INPersonHandleTypeUnknown] nameComponents:nameComponents displayName:message.fromName image:avatarImage contactIdentifier:nil customIdentifier:message.fromUsername isMe:NO suggestionType:(INPersonSuggestionTypeNone)];

                    INSendMessageIntent *intent = [[INSendMessageIntent alloc] initWithRecipients:@[messageSender] outgoingMessageType:(INOutgoingMessageTypeOutgoingMessageText) content:contentAttribut.string speakableGroupName:[[INSpeakableString alloc]initWithSpokenPhrase:@""] conversationIdentifier:message.msgId serviceName:nil sender:messageSender attachments:nil];
                    [intent setImage:avatarImage forParameterNamed:@"speakableGroupName"];

                    INInteraction *interaction = [[INInteraction alloc]initWithIntent:intent response:nil];
                    interaction.direction = INInteractionDirectionIncoming;
                    [interaction donateInteractionWithCompletion:nil];

                    
                    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:message.msgId content:[content contentByUpdatingWithProvider:intent error:nil] trigger:nil];
                    
                    [center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) {
    
    
                        NSLog(@"成功添加推送");
                    }];
                }];
            }else{
    
    
                UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:message.msgId content:content trigger:nil];
                [center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) {
    
    
                    NSLog(@"成功添加推送");
                }];
            }
        }else{
    
    
            UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:message.msgId content:content trigger:nil];
            [center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) {
    
    
                NSLog(@"成功添加推送");
            }];
        }
Remote notification-realize communication notification
1. First add notification extension ( Notification Service Extension)

Notifications after iOS10 have extended functions that can do something when the system receives notifications and displays notifications.
Insert image description here

2. Add the following key-value pairs to the notification extension
<key>NSUserActivityTypes</key>
   <array>
   	<string>INStartCallIntent</string>
   	<string>INSendMessageIntent</string>
   </array>

Insert image description here

3. In NotificationServicethe following method under notification extension, communication notification is implemented. The specific implementation method is similar to local push.
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    
    
}

The core code is as follows:

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    
    
    
    self.bestAttemptContent = [request.content mutableCopy];
    
    if (@available(iOS 15.0, *)) {
    
    
        //实现消息内容展示
        // 发送者名称
        NSString *fromUsername = self.bestAttemptContent.userInfo[@"xxx"];
        // 发送者头像url地址
        NSString *fromAvatar = self.bestAttemptContent.userInfo[@"xxx"];
        // 发送者昵称
        NSString *fromNickName = self.bestAttemptContent.userInfo[@"xxx"];
        // 消息 id
        NSString *messageId = self.bestAttemptContent.userInfo[@"xxx"];
        if (fromUsername && fromAvatar && fromNickName && messageId)
        {
    
    
            //需要先下载图片
            NSURL *imageURL = [NSURL URLWithString:fromAvatar];
            __block INImage *avatarImage = nil;
            
            [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:imageURL completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
    
    
                if (image) {
    
    
                    avatarImage = [INImage imageWithImageData:data];
                }
                // 消息发送方
                NSPersonNameComponents *nameComponents = [[NSPersonNameComponents alloc] init];
                nameComponents.nickname = fromUsername;// 用户名
                
                INPerson *messageSender = [[INPerson alloc]initWithPersonHandle:[[INPersonHandle alloc]initWithValue:nil type:INPersonHandleTypeUnknown] nameComponents:nameComponents displayName:fromNickName image:avatarImage contactIdentifier:nil customIdentifier:fromUsername isMe:NO suggestionType:(INPersonSuggestionTypeNone)];
                
                INSendMessageIntent *intent = [[INSendMessageIntent alloc] initWithRecipients:@[messageSender] outgoingMessageType:(INOutgoingMessageTypeOutgoingMessageText) content:self.bestAttemptContent.body speakableGroupName:[[INSpeakableString alloc]initWithSpokenPhrase:@""] conversationIdentifier:messageId serviceName:nil sender:messageSender attachments:nil];
                [intent setImage:avatarImage forParameterNamed:@"speakableGroupName"];
                
                INInteraction *interaction = [[INInteraction alloc]initWithIntent:intent response:nil];
                interaction.direction = INInteractionDirectionIncoming;
                [interaction donateInteractionWithCompletion:nil];
                
                self.bestAttemptContent =  [[request.content contentByUpdatingWithProvider:intent error:nil] mutableCopy];
            }];
            
        }else{
    
    
            contentHandler(self.bestAttemptContent);
        }
    }else{
    
    
        contentHandler(self.bestAttemptContent);
    }
}
Effect

At this point, the communication notification function is completed and can be tested. The effect after our implementation is as follows:
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_36162680/article/details/126973540