IOS / Obj-C - fire alarm without a timer?

I want to configure some local notifications in my iOS application, however, every tutorial that I seem to have discovered when implementing it, apparently only allows me to send a notification based on a timer (see code example below)? Is it possible to run a local notification, for example, when new data is loaded into a UITableView? Sorry for the general question, but I can not find a lot of documentation about this. I'm also not sure how to do this if the data is captured only when my user hits the screen? For example, data is captured / updated in viewDidLoad from ViewController?

-(void)viewDidLoad { UILocalNotification *localNotification = [[UILocalNotification alloc] init]; localNotification.fireDate = dateTime; localNotification.alertBody = [NSString stringWithFormat:@"Alert Fired at %@", dateTime]; localNotification.soundName = UILocalNotificationDefaultSoundName; localNotification.applicationIconBadgeNumber = 1; [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; } 
+5
source share
5 answers

First of all, you should consider the fact that the UILocalNotification class that you are using has been deprecated since iOS 10. Since iOS 10 there is no difference between local and remote notifications.

In the UserNotifications framework (iOS 10.0+, Swift | Objective-C), UNNotification instances are not created, as in some previous implementations of similar Apple frameworks / APIs. Instead, the UNNotificationCenter instance UNNotificationCenter responsible for creating notification objects and invokes delegation methods when new notifications are received and before the default user interface is displayed. For more information on UNUserNotificationCenterDelegate protocol UNUserNotificationCenterDelegate see Apple documentation . I often end up using AppDelegate as a class conforming to this protocol

Now back to the question. To initiate the creation of a notification from the application first, you must create a trigger (in your case, you can use the UNTime​Interval​Notification​Trigger ), then create a notification request and, finally, add the request to the plain notification center, which can be accessed by calling UNUserNotificationCenter.current() .

 let content = UNMutableNotificationContent() content.title = "Alert Fired" 

Create a trigger that determines when UNUserNotificationCenter triggers a notification

 let trigger = UNTime​Interval​Notification​Trigger(timeInterval: 0, repeats: false) 

Create a notification request. You only create those that trigger local notifications, since iOS is responsible for creating request objects for incoming push notifications.

 let request = UNNotificationRequest(identifier: "FiveSecond", content: content, trigger: trigger) 

Now we will need to add our request to the current notification center associated with our application.

 let center = UNUserNotificationCenter.current() center.add(request, withCompletionHandler: nil) 

In our case, the notification will be immediately initiated by the UNUserNotificationCenter.

+4
source

You can use the postNotificationName method as follows:

 MyCustomObject *customObject = [MyCustomObject new]; [[NSNotificationCenter defaultCenter] postNotificationName:@"Your notification name" object:customObject]; 

Processing an object passing through a sent notification will look something like this. Obviously, I am only registering here, but you can process it as you like.

 - (void)methodToProcessNotificationData:(NSNotification *)notification { NSLog(@"%@",notification.object); } 

If you want the class to listen for a notification, you can do something like the following code snippet. This adds an observer to the class, gives it the method to be called (in this case methodToProcessNotificationData), and the name of the notification you want to listen to.

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(methodToProcessNotificationData:) name:@"Your notification name" object:nil]; 
+2
source

Instead, you can use the method below:

 - (void)postNotificationName:(NSNotificationName)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo; 

[1] https://developer.apple.com/reference/foundation/nsnotificationcenter/1410608-postnotificationname?language=objc

+1
source

You can simply specify the time as [NSDate date] when you want to run a local notification. It will trigger a notification at this time.

+1
source

The first thing to know is why you need a local local notification

 // Handle launching from a notification if(IOS_VERSION<10) { UILocalNotification *locationNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]; if (locationNotification) { // Set icon badge number to zero application.applicationIconBadgeNumber = 0; } if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) { [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge| UIUserNotificationTypeSound categories:nil]]; } 

} yet {

 [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) { // Enable or disable features based on authorization. }]; 

}

and the last thing

  if(IOS_VERSION<10){ [[UIApplication sharedApplication] cancelAllLocalNotifications]; NSLog(@"LocalNotifications]count %d",(int) [[[UIApplication sharedApplication] scheduledLocalNotifications]count]); NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar] ; NSDate *now = [NSDate date]; NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:now]; [components setHour:15]; [components setMinute:35]; UILocalNotification *notification = [[UILocalNotification alloc]init]; notification.fireDate = [calendar dateFromComponents:components]; notification.repeatInterval = NSCalendarUnitDay; notification.alertBody =@ "message"; notification.applicationIconBadgeNumber = 0; notification.soundName = UILocalNotificationDefaultSoundName; [[UIApplication sharedApplication] scheduleLocalNotification:notification]; }else{ [[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests]; NSLog(@"LocalNotifications]count %d",(int) [[[UIApplication sharedApplication] scheduledLocalNotifications]count]); NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar] ; NSDate *now = [NSDate date]; NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:now]; [components setHour:15]; [components setMinute:35]; UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init]; // objNotificationContent.title = [NSString localizedUserNotificationStringForKey:NotificationHeading arguments:nil]; objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@"message" arguments:nil]; objNotificationContent.sound = [UNNotificationSound defaultSound]; /// 4. update application icon badge number objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber]); // UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger // triggerWithTimeInterval:60 repeats:YES]; UNCalendarNotificationTrigger *trigger2 = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES]; UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond" content:objNotificationContent trigger:trigger2]; /// 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"); } }]; } 
0
source

Source: https://habr.com/ru/post/1266027/


All Articles