iOS本地推送

來源:互聯網
上載者:User

標籤:require   interval   技術   alert   tno   sys   wak   lse   pre   

通過iOS本地推送實現定時推送

  • 先在appdelegate的didFinishLaunch方法中請求推送許可
    if (@available(iOS 10.0, *)) {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert+UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) { }]; center.delegate = self; } else { // Fallback on earlier versions [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:[NSSet set]] ]; }

     

  •   收到本地通知的處理
//iOS10之前收到本地通知
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{ NSLog(@"receive local notifi%@",notification.userInfo);}
//iOS10以後,這個代理代表app在前台的時候
 - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler NS_AVAILABLE_IOS(10){ 

  NSLog(@"willPresentNotification local notifi%@",notification.request.content.userInfo);
  //代表交給didReceiveNotificationResponse處理
  completionHandler(UNNotificationPresentationOptionSound); 
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler NS_AVAILABLE_IOS(10){ NSLog(@"userNotificationCenter local notifi%@",response.notification.request.content.userInfo); if ([response.actionIdentifier isEqualToString:@"sure"]) { NSLog(@"notif sure"); }else if ([response.actionIdentifier isEqualToString:@"cancel"]){ NSLog(@"notif cancel"); } completionHandler();}

 設定本地推送

- (void)addAlarmIndentifier:(NSString*)requestIndetifier isRepeat:(BOOL)repeat{    NSDateComponents*cmp = [[NSCalendar currentCalendar] components:NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitWeekday fromDate:self.datepicker.date];    NSDateComponents *components = [[NSDateComponents alloc] init];    components.hour = cmp.hour;    components.minute = cmp.minute  ;    components.weekday = cmp.weekday;    //通知聲音    NSString *soundName =  @"soundName";    if (@available(iOS 10.0, *)) {        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];        content.title = @"wake up!!";        content.body = @"time to massage" ;        //類別,用於自訂通知動作        content.categoryIdentifier = @"alarm";        content.userInfo [email protected]{@"name":@"jack"};             //通知聲音        content.sound = [UNNotificationSound soundNamed:soundName];        //觸發器repeats:代表是否重複        UNCalendarNotificationTrigger *trig = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:(repeat?YES:NO)];        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIndetifier content:content trigger:trig];        //動作1        UNNotificationAction*action1 = [UNNotificationAction actionWithIdentifier:@"sure" title:@"sure" options:UNNotificationActionOptionForeground];        //動作2        UNNotificationAction*action2 = [UNNotificationAction actionWithIdentifier:@"cacel" title:@"cancel" options:UNNotificationActionOptionAuthenticationRequired];        //identifier:alarm        UNNotificationCategory*category =    [UNNotificationCategory categoryWithIdentifier:@"alarm" actions:@[action1,action2] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];        //設定分類        [center setNotificationCategories: [NSSet setWithObject:category]];        //設定通知        [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {            if (error) {                NSLog(@"error===%@",error.localizedDescription);            }        }];                    } else {//ios 10 以下        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm";        UILocalNotification *notification       = [[UILocalNotification alloc] init];        //如果需要迴圈可以以過去的時間為標準,然後設定repeatInterval        notification.fireDate  = self.datepicker.date;                notification.repeatCalendar             = [NSCalendar currentCalendar];        notification.repeatInterval             = repeat?NSCalendarUnitWeekOfYear:0;        //        //    NSMinuteCalendarUnit        notification.timeZone                   = [NSTimeZone systemTimeZone];        notification.alertBody                  = @"wake up!!!";        notification.soundName                  = soundName;        [[UIApplication sharedApplication] scheduleLocalNotification:notification];    }    }

取消通知(全部取消)

- (void)cancel{     if (@available(iOS 10.0, *)) {        [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];    } else {          [[UIApplication sharedApplication] cancelAllLocalNotifications];    }}
  • 效果如:

iOS本地推送

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.