本地定時推送代碼實現 IOS10以上

//定時推送.net

+ (void)createLocalizedUserNotification{orm

 

    // 設置觸發條件 UNNotificationTrigger對象

    //timeInterval:單位爲秒(s)repeats:是否循環提醒get

    UNTimeIntervalNotificationTrigger *timeTrigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:YES];string

 

    // 建立通知內容 UNMutableNotificationContent, 注意不是 UNNotificationContent ,此對象爲不可變對象。it

    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];io

    content.title = @"Dely 時間提醒 - title";table

    content.subtitle = [NSString stringWithFormat:@"Dely 裝逼大會競選時間提醒 - subtitle"];class

    content.body = @"Dely 裝逼大會總決賽時間到,歡迎你參加總決賽!但願你一統X界 - body";循環

    content.badge = @666;

    content.sound = [UNNotificationSound defaultSound];

    content.userInfo = @{@"key1":@"value1",@"key2":@"value2"};

 

    // 建立通知標示

    NSString *requestIdentifier = @"Dely.X.time";

 

    // 建立通知請求 UNNotificationRequest 將觸發條件和通知內容添加到請求中

    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifier content:content trigger:timeTrigger];

 

    UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];

    // 將通知請求 add 到 UNUserNotificationCenter

    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {

        if (!error) {

            NSLog(@"推送已添加成功 %@", requestIdentifier);

            //你本身的需求例以下面:

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"本地通知" message:@"成功添加推送" preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];

            [alert addAction:cancelAction];

            [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];

        }

    }];

 

}

相關文章
相關標籤/搜索