ios 接收到推送消息时实现持续响铃震动效果

项目中需要实现一个功能:收到特定类型的推送消息时,需要一端持续的响铃加震动来提醒用户,普通的推送消息可以播放30s以内的提示音,但是只会震动一下,用ios提供的Notification Service Extension 可以实现连续震动的效果,它不依赖于APP的存活状态,会最多存活30s的时间。具体实现方式如下:
1,创建Notification Service Extension扩展

image.png

创建完成后,会自动生成以下两个方法:

@interface NotificationService ()
@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;
//振动计时器
@property (nonatomic, strong, nullable) dispatch_source_t vibrationTimer;

@end

//收到推送消息后,会先执行此方法
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    //开始震动
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    NSDictionary *pushDictionary = request.content.userInfo;
    if([pushDictionary.allKeys containsObject:@"act"]){
        NSInteger act = [pushDictionary[@"act"] integerValue];
        //判断是否是需要持续震动的通知类型
        if(act == 4){
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            if (self.vibrationTimer) {
                dispatch_cancel(self.vibrationTimer);
                self.vibrationTimer = nil;
            }
            self.vibrationTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
            dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
            uint64_t interval = 1 * NSEC_PER_SEC;
            dispatch_source_set_timer(self.vibrationTimer, start, interval, 0);
            __block int times = 0;
            //最多震动20次,或者用户点击了推送的通知,则停止震动
            dispatch_source_set_event_handler(self.vibrationTimer, ^{
                self.contentHandler(self.bestAttemptContent);
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
                times++;
                NSUserDefaults *userDefault = [[NSUserDefaults alloc]initWithSuiteName:@"group.com.XXXXXX"];
                NSString *status = [userDefault objectForKey:@"status"];
                if(times >=20 ||[status isEqualToString:@"1"]){
                    dispatch_suspend(self.vibrationTimer);
                    dispatch_cancel(self.vibrationTimer);
                }
            });
            dispatch_resume(self.vibrationTimer);
        } else {
            self.contentHandler(self.bestAttemptContent);
        }
    } else {
        self.contentHandler(self.bestAttemptContent);
    }
}

//如果在30s内还没有执行完想要执行的任务,就会执行这个方法
- (void)serviceExtensionTimeWillExpire {
    // Called just before the extension will be terminated by the system.
    // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
    if (self.vibrationTimer) {
        dispatch_cancel(self.vibrationTimer);
        self.vibrationTimer = nil;
    }
    self.contentHandler(self.bestAttemptContent);
}

这里有三点需要注意:
1,只有调用self.contentHandler(self.bestAttemptContent);回调方法时,推送的通知条消息才会出现在应用中,如果一直不回调该方法,等30s后,系统会自动调用- (void)serviceExtensionTimeWillExpire方法;
2:ios的服务扩展可以和app进行通信,有多种通信方式比如利用通知中心 CFNotificationCenterRef,或者socket,这里我选择使用的是共享内存的方式:

NSUserDefaults *userDefault = [[NSUserDefaults alloc]initWithSuiteName:@"group.com.XXXXXX"];
NSString *status = [userDefault objectForKey:@"status"];

"group.com.XXXXXX" 需要自己创建一个共享内存的组名,当用户点击推送通知时,根据名称找到当前内存,并设置一个值,在扩展中就能够获取该值了。

NSUserDefaults *userDefault = [[NSUserDefaults alloc]initWithSuiteName:@"group.com.net263.263Vision"];
[userDefault setObject:@"1" forKey:@"status"];

2,在扩展中,使用NSTimer作为计时器时,自测无效(个人认为因为NSTimer运行依赖于NSRunLoop导致的),无法触发计时器运行,使用dispatch_source_t能够很好地运行。
3,要想在扩展中接收到推送的消息,推送消息中还应该增加一个字段:“mutable-content”: 1

版权声明:
作者:倾城
链接:https://www.techfm.club/p/42412.html
来源:TechFM
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>