如何在iOS 10中安排本地通知(objective-c)

时间:2022-09-02 10:50:21

I'd like to schedule local notifications using iOS 10. I'd like to know how to do this. I've looked all around the web, but I keep finding clues only for registering and handeling the notifications. Not for the scheduling of a local notification.

我想使用iOS 10安排本地通知。我想知道如何做到这一点。我一直在网上看,但我一直在寻找线索,只是为了注册和处理通知。不适用于本地通知的安排。

So, does anyone know how to do this?

那么,有谁知道怎么做?

2 个解决方案

#1


16  

  1. Try it. Its deprecated but working code. Use it for Before iOS 10.0 :

    试试吧。它已弃用但工作代码。在iOS 10.0之前使用它:

    //Get all previous noti..
     NSLog(@"scheduled notifications: --%@----", [[UIApplication sharedApplication] scheduledLocalNotifications]);
    
     NSDate *now = [NSDate date];
     now = [now dateByAddingTimeInterval:60*60*24*7]; //7 for 7th day of the week.
     NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    [calendar setTimeZone:[NSTimeZone localTimeZone]];
     NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSTimeZoneCalendarUnit fromDate:now];
    
    
     NSDate *SetAlarmAt = [calendar dateFromComponents:components];
    
    
     UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    
     localNotification.fireDate = SetAlarmAt;
    
    
     NSLog(@"FIRE DATE --%@----",[SetAlarmAt description]);
    
     localNotification.alertBody =@"Alert";
    
     localNotification.alertAction = [NSString stringWithFormat:@"My test for Weekly alarm"];
    
     localNotification.userInfo = @{
                               @"alarmID":[NSString stringWithFormat:@"123"],
                               @"SOUND_TYPE":[NSString stringWithFormat:@"hello.mp3"]
                               };
    
      localNotification.repeatInterval=0; //[NSCalendar currentCalendar];
    
    
      [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    
    1. For iOS 10.0 and later: Now try with UserNotifications framework: Add the framework, and import like #import . In Appdelegate Didfinishluanch method.

      对于iOS 10.0及更高版本:现在尝试使用UserNotifications框架:添加框架,并像#import一样导入。在Appdelegate Didfinishluanch方法。

      UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
          [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
                    completionHandler:^(BOOL granted, NSError * _Nullable error) {
                        if (!error) {
                            NSLog(@"request succeeded!");
                            [self testAlrt];
                        }
                    }];
      

In your ibaction or method, write it and test:

在你的ibaction或方法中,写下它并测试:

 NSDate *now = [NSDate date];

// NSLog(@"NSDate--before:%@",now);

now = [now dateByAddingTimeInterval:60*60*24*7];

NSLog(@"NSDate:%@",now);

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

[calendar setTimeZone:[NSTimeZone localTimeZone]];

NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSTimeZoneCalendarUnit fromDate:now];

NSDate *todaySehri = [calendar dateFromComponents:components]; //unused



UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@"Notification!" arguments:nil];
objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@"This is local notification message!"
                                                                    arguments:nil];
objNotificationContent.sound = [UNNotificationSound defaultSound];

/// 4. update application icon badge number
objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);


UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:NO];


UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"ten"
                                                                      content:objNotificationContent trigger:trigger];
/// 3. schedule localNotification
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    if (!error) {
        NSLog(@"Local Notification succeeded");
    }
    else {
        NSLog(@"Local Notification failed");
    }
}];

#2


8  

Follow the step: 1. Import UserNotifications.framework and go to your AppDelegate class.

按照以下步骤操作:1。导入UserNotifications.framework并转到AppDelegate类。

In .h

#import <UserNotifications/UserNotifications.h>
@interface AppDelegate : UIResponder          <UIApplicationDelegate,UNUserNotificationCenterDelegate>

@end
  1. Register for push :

    注册推送:

    #define SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending) 
    

Now add this in did finish launching :

现在添加这个完成启动:

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
   [self registerForRemoteNotifications];
return YES;
}

 - (void)registerForRemoteNotifications {
  if(SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(@"10.0")){
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
         if(!error){
             [[UIApplication sharedApplication] registerForRemoteNotifications];
         }
     }];  
}
else {
    // Code for old versions
}
}
  1. Delegate methods for UserNotifications :

    用户通知的委托方法:

      //Called when a notification is delivered to a foreground app.
    
     -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
    NSLog(@"User Info : %@",notification.request.content.userInfo);
    completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
    }
    
     //Called to let your app know which action was selected by the user for a given notification.
     -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
     NSLog(@"User Info : %@",response.notification.request.content.userInfo);
      completionHandler();
      }
    
  2. Push Notifications Entitlements : From project target’s Capabilities tab and add Push Notifications Entitlements. 如何在iOS 10中安排本地通知(objective-c)

    推送通知权利:从项目目标的功能选项卡中添加推送通知权利。

  3. Add push and mobile certificate properly. Hope this is everything you need!

    正确添加推送和移动证书。希望这是你需要的一切!

For more info: http://ashishkakkad.com/2016/09/push-notifications-in-ios-10-objective-c/

欲了解更多信息:http://ashishkakkad.com/2016/09/push-notifications-in-ios-10-objective-c/

#1


16  

  1. Try it. Its deprecated but working code. Use it for Before iOS 10.0 :

    试试吧。它已弃用但工作代码。在iOS 10.0之前使用它:

    //Get all previous noti..
     NSLog(@"scheduled notifications: --%@----", [[UIApplication sharedApplication] scheduledLocalNotifications]);
    
     NSDate *now = [NSDate date];
     now = [now dateByAddingTimeInterval:60*60*24*7]; //7 for 7th day of the week.
     NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    [calendar setTimeZone:[NSTimeZone localTimeZone]];
     NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSTimeZoneCalendarUnit fromDate:now];
    
    
     NSDate *SetAlarmAt = [calendar dateFromComponents:components];
    
    
     UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    
     localNotification.fireDate = SetAlarmAt;
    
    
     NSLog(@"FIRE DATE --%@----",[SetAlarmAt description]);
    
     localNotification.alertBody =@"Alert";
    
     localNotification.alertAction = [NSString stringWithFormat:@"My test for Weekly alarm"];
    
     localNotification.userInfo = @{
                               @"alarmID":[NSString stringWithFormat:@"123"],
                               @"SOUND_TYPE":[NSString stringWithFormat:@"hello.mp3"]
                               };
    
      localNotification.repeatInterval=0; //[NSCalendar currentCalendar];
    
    
      [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    
    1. For iOS 10.0 and later: Now try with UserNotifications framework: Add the framework, and import like #import . In Appdelegate Didfinishluanch method.

      对于iOS 10.0及更高版本:现在尝试使用UserNotifications框架:添加框架,并像#import一样导入。在Appdelegate Didfinishluanch方法。

      UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
          [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
                    completionHandler:^(BOOL granted, NSError * _Nullable error) {
                        if (!error) {
                            NSLog(@"request succeeded!");
                            [self testAlrt];
                        }
                    }];
      

In your ibaction or method, write it and test:

在你的ibaction或方法中,写下它并测试:

 NSDate *now = [NSDate date];

// NSLog(@"NSDate--before:%@",now);

now = [now dateByAddingTimeInterval:60*60*24*7];

NSLog(@"NSDate:%@",now);

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

[calendar setTimeZone:[NSTimeZone localTimeZone]];

NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSTimeZoneCalendarUnit fromDate:now];

NSDate *todaySehri = [calendar dateFromComponents:components]; //unused



UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@"Notification!" arguments:nil];
objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@"This is local notification message!"
                                                                    arguments:nil];
objNotificationContent.sound = [UNNotificationSound defaultSound];

/// 4. update application icon badge number
objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);


UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:NO];


UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"ten"
                                                                      content:objNotificationContent trigger:trigger];
/// 3. schedule localNotification
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    if (!error) {
        NSLog(@"Local Notification succeeded");
    }
    else {
        NSLog(@"Local Notification failed");
    }
}];

#2


8  

Follow the step: 1. Import UserNotifications.framework and go to your AppDelegate class.

按照以下步骤操作:1。导入UserNotifications.framework并转到AppDelegate类。

In .h

#import <UserNotifications/UserNotifications.h>
@interface AppDelegate : UIResponder          <UIApplicationDelegate,UNUserNotificationCenterDelegate>

@end
  1. Register for push :

    注册推送:

    #define SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending) 
    

Now add this in did finish launching :

现在添加这个完成启动:

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
   [self registerForRemoteNotifications];
return YES;
}

 - (void)registerForRemoteNotifications {
  if(SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(@"10.0")){
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
         if(!error){
             [[UIApplication sharedApplication] registerForRemoteNotifications];
         }
     }];  
}
else {
    // Code for old versions
}
}
  1. Delegate methods for UserNotifications :

    用户通知的委托方法:

      //Called when a notification is delivered to a foreground app.
    
     -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
    NSLog(@"User Info : %@",notification.request.content.userInfo);
    completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
    }
    
     //Called to let your app know which action was selected by the user for a given notification.
     -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
     NSLog(@"User Info : %@",response.notification.request.content.userInfo);
      completionHandler();
      }
    
  2. Push Notifications Entitlements : From project target’s Capabilities tab and add Push Notifications Entitlements. 如何在iOS 10中安排本地通知(objective-c)

    推送通知权利:从项目目标的功能选项卡中添加推送通知权利。

  3. Add push and mobile certificate properly. Hope this is everything you need!

    正确添加推送和移动证书。希望这是你需要的一切!

For more info: http://ashishkakkad.com/2016/09/push-notifications-in-ios-10-objective-c/

欲了解更多信息:http://ashishkakkad.com/2016/09/push-notifications-in-ios-10-objective-c/