在 ios 11 目标 c 中的特定时间安排每日本地通知



我必须每天在特定时间安排本地通知,我已经完成了一些代码,但通知来了很多次 提前致谢

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions options = UNAuthorizationOptionAlert + UNAuthorizationOptionSound;
[center requestAuthorizationWithOptions:options completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!granted) {
NSLog(@"Something went wrong");
center.delegate = self;
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
}
else
{
[self scheduleLocalNotifications];
}

}];
}

函数调用为

- (void)scheduleLocalNotifications 
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute|NSCalendarUnitSecond) fromDate:now];
[components setHour:8];
[components setMinute:00];
[components setSecond:00];
// Gives us today's date but at 9am
NSDate *next8am = [calendar dateFromComponents:components];
if ([next8am timeIntervalSinceNow] < 0) {
// If today's 9am already occurred, add 24hours to get to tomorrow's
next8am = [next8am dateByAddingTimeInterval:60*60*24];
}
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = next8am;
notification.alertTitle = @"------App";
notification.alertBody = @"You may have new notifications...";
// Set a repeat interval to daily
notification.repeatInterval = NSCalendarUnitDay;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];}
import UserNotifications
let trigger = UNCalendarNotificationTrigger(dateMatching: D 
ateComponents(hour: 20, minute: 00), repeats: true)
print(trigger.nextTriggerDate() ?? "nil")
let content = UNMutableNotificationContent()
content.title = "title"
content.body = "body"
// make sure you give each request a unique identifier. (nextTriggerDate 
description)
let request = UNNotificationRequest(identifier: "identify", content: content, 
trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print(error)
return
}
print("scheduled")
}

不要忘记请求用户在您的应用程序代理中计划通知的权限:

func application(_ application: UIApplication, didFinishLaunchingWithOptions 
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, 
.alert, .sound]) { granted, error in
// your code
}
return true
}

最新更新