ios 接收到推送消息時實現(xiàn)持續(xù)響鈴震動效果

項目中需要實現(xiàn)一個功能:收到特定類型的推送消息時,需要一端持續(xù)的響鈴加震動來提醒用戶,普通的推送消息可以播放30s以內的提示音,但是只會震動一下,用ios提供的Notification Service Extension 可以實現(xiàn)連續(xù)震動的效果,它不依賴于APP的存活狀態(tài),會最多存活30s的時間。具體實現(xiàn)方式如下:
1,創(chuàng)建Notification Service Extension擴展


image.png

創(chuàng)建完成后,會自動生成以下兩個方法:

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

@end

//收到推送消息后,會先執(zhí)行此方法
- (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];
        //判斷是否是需要持續(xù)震動的通知類型
        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內還沒有執(zhí)行完想要執(zhí)行的任務,就會執(zhí)行這個方法
- (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);回調方法時,推送的通知條消息才會出現(xiàn)在應用中,如果一直不回調該方法,等30s后,系統(tǒng)會自動調用- (void)serviceExtensionTimeWillExpire方法;
2:ios的服務擴展可以和app進行通信,有多種通信方式比如利用通知中心 CFNotificationCenterRef,或者socket,這里我選擇使用的是共享內存的方式:

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

"group.com.XXXXXX" 需要自己創(chuàng)建一個共享內存的組名,當用戶點擊推送通知時,根據(jù)名稱找到當前內存,并設置一個值,在擴展中就能夠獲取該值了。

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

2,在擴展中,使用NSTimer作為計時器時,自測無效(個人認為因為NSTimer運行依賴于NSRunLoop導致的),無法觸發(fā)計時器運行,使用dispatch_source_t能夠很好地運行。
3,要想在擴展中接收到推送的消息,推送消息中還應該增加一個字段:“mutable-content”: 1

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容