Run local notification at specific times in iOS

I am trying to create a timer that starts a local notification in order to leave at the time that the user set. The problem I am facing is that I cannot figure out how to set up a local notification, for example, at 7:00 in the evening. Nearly all of the methods discovered by investigating this problem included local notification sent at a specific time from the current date. I am trying to allow the user to select 7:00 PM and then remove the notification at this time. It is logical that this can be achieved due to the final time (user-selected value) - the current time, which will give you the time difference. However, I'm not quite sure how to do this.

Any help regarding this topic would be greatly appreciated, thanks. Below is the code that I use to trigger a local notification.

let center = UNUserNotificationCenter.current() content.title = storedMessage content.body = "Drag down to reset or disable alarm" content.categoryIdentifier = "alarm" content.userInfo = ["customData": "fizzbuzz"] content.sound = UNNotificationSound.init(named: "1.mp3") content.badge = 1 let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeAmount, repeats: false) let request = UNNotificationRequest(identifier: "requestAlarm", content: content, trigger: trigger) center.add(request) center.delegate = self 
+15
ios time timer swift uilocalnotification
source share
5 answers

Well, in iOS 10, Apple has deprecated UILocalNotification, which means it's time to familiarize yourself with the new notification system.

Customization This is a long post, so you can easily start by importing a new notification structure:

 // Swift import UserNotifications // Objective-C (with modules enabled) @import UserNotifications; 

Managing notifications through a common UNUserNotificationCenter object:

 // Swift let center = UNUserNotificationCenter.current() // Objective-C UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; 

Authorization As with the earlier notification structure, you must have user permission for the types of notifications that your application will use. Make a request at an early stage in your application life cycle, for example in the application: didFinishLaunchingWithOptions :. The first time you authorize your application, the system displays a warning to the user, after which they can manage permissions from the settings:

 // Swift let options: UNAuthorizationOptions = [.alert, .sound]; // Objective-C UNAuthorizationOptions options = UNAuthorizationOptionAlert + UNAuthorizationOptionSound; 

You make the actual authorization request using the general notification center:

 // Swift center.requestAuthorization(options: options) { (granted, error) in if !granted { print("Something went wrong") } } // Objective-C [center requestAuthorizationWithOptions:options completionHandler:^(BOOL granted, NSError * _Nullable error) { if (!granted) { NSLog(@"Something went wrong"); } }]; 

The structure calls a termination handler with a boolean indicating whether access was granted and an error object that will be zero if no error occurs.

Note. The user can change the notification settings for your application at any time. You can check the allowed settings using the getNotificationSettings method. This asynchronously calls the termination block with the UNNotificationSettings object, which you can use to check the authorization status or individual notification settings:

  // Swift center.getNotificationSettings { (settings) in if settings.authorizationStatus != .authorized { // Notifications not allowed } } // Objective-C [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { if (settings.authorizationStatus != UNAuthorizationStatusAuthorized) { // Notifications not allowed } }]; 

Creating a notification request The notification request UNNotificationRequest contains the content and trigger condition:

Notification Content

The contents of the notification is an instance of the UNMutableNotificationContent object with the following parameters set as necessary:

title: A string containing the root cause of the warning.

subtitles: a string containing warning subtitles (if required)

body: String containing the text of the warning message

Icon

: number to display on the application icon.

sound: the sound that will be played when an alert is given. Use UNNotificationSound.default () or create a custom sound from a file. launchImageName: The name of the launch image that will be used when the application starts in response to a notification.

userInfo: a dictionary of user information to pass in the notification Attachments: an array of UNNotificationAttachment objects. Use to enable audio, image or video content.

Note that when localizing warning lines, such as a header, it is better to use localizedUserNotificationString (forKey: arguments :), which delays loading localization until a notification is sent.

Quick example:

  // Swift let content = UNMutableNotificationContent() content.title = "Don't forget" content.body = "Buy some milk" content.sound = UNNotificationSound.default() // Objective-C UNMutableNotificationContent *content = [UNMutableNotificationContent new]; content.title = @"Don't forget"; content.body = @"Buy some milk"; content.sound = [UNNotificationSound defaultSound]; 

Notification alert

Start notifications about time, calendar or location. The trigger can be repeated:

Time Interval: Schedule a notification a few seconds later. For example, to start in five minutes:

  // Swift let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 300, repeats: false) // Objective-C UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:300 repeats:NO]; 

Calendar: Launch at a specific date and time. A trigger is created using the date component component, which simplifies some recurring intervals. To convert a date to its date, components use the current calendar. For example:

  // Swift let date = Date(timeIntervalSinceNow: 3600) let triggerDate = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date) // Objective-C NSDate *date = [NSDate dateWithTimeIntervalSinceNow:3600]; NSDateComponents *triggerDate = [[NSCalendar currentCalendar] components:NSCalendarUnitYear + NSCalendarUnitMonth + NSCalendarUnitDay + NSCalendarUnitHour + NSCalendarUnitMinute + NSCalendarUnitSecond fromDate:date]; 

To create a trigger from date components:

  // Swift let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false) // Objective-C UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:triggerDate repeats:NO]; 

To create a trigger that repeats at a specific interval, use the correct set of date components. For example, for the daily notification to be repeated, we only need an hour, minutes and seconds:

  let triggerDaily = Calendar.current.dateComponents([hour, .minute, .second], from: date) let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true) 

To repeat weekly at the same time, we also need a weekday:

  let triggerWeekly = Calendar.current.dateComponents([.weekday, .hour, .minute, .second], from: date) let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true) 

Planning

In preparing the content and trigger, we create a new notification request and add it to the notification center. For each notification request, a line identifier is required for future reference:

  // Swift let identifier = "UYLLocalNotification" let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) center.add(request, withCompletionHandler: { (error) in if let error = error { // Something went wrong } }) // Objective-C NSString *identifier = @"UYLLocalNotification"; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger] [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (error != nil) { NSLog(@"Something went wrong: %@",error); } }]; 
+54
source share

To run a notification about a specific time, use the code below.

 let content = UNMutableNotificationContent() content.title = "Title" content.body = "Body" content.sound = UNNotificationSound.default() let gregorian = Calendar(identifier: .gregorian) let now = Date() var components = gregorian.dateComponents([.year, .month, .day, .hour, .minute, .second], from: now) // Change the time to 7:00:00 in your locale components.hour = 7 components.minute = 0 components.second = 0 let date = gregorian.date(from: components)! let triggerDaily = Calendar.current.dateComponents([.hour,.minute,.second,], from: date) let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true) let request = UNNotificationRequest(identifier: CommonViewController.Identifier, content: content, trigger: trigger) print("INSIDE NOTIFICATION") UNUserNotificationCenter.current().add(request, withCompletionHandler: {(error) in if let error = error { print("SOMETHING WENT WRONG") } }) 

And to start constantly after a certain period of time, for example, every 2 minutes, use the following line to start.

 let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 120, repeats: true) 
+5
source share

For Swift, you can use this code:

  let calendar = Calendar.current let components = DateComponents(year: 2018, month: 05, day: 06, hour: 20, minute: 22) // Set the date here when you want Notification let date = calendar.date(from: components) let comp2 = calendar.dateComponents([.year,.month,.day,.hour,.minute], from: date!) let trigger = UNCalendarNotificationTrigger(dateMatching: comp2, repeats: true) let content = UNMutableNotificationContent() content.title = "Notification Demo" content.subtitle = "Demo" content.body = "Notification on specific date!!" let request = UNNotificationRequest( identifier: "identifier", content: content, trigger: trigger ) UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in if error != nil { //handle error } else { //notification set up successfully } }) 

Hope this helps.

+2
source share

try this

  let dateformateer = NSDateFormatter() dateformateer.timeStyle = .ShortStyle let notification = UILocalNotification() var datecomponent = NSDateComponents() datecomponent = NSCalendar.currentCalendar().components([NSCalendarUnit.Day,NSCalendarUnit.Month,NSCalendarUnit.Hour,NSCalendarUnit.Year, NSCalendarUnit.Minute],fromDate: Datepicker.date) var fixdate = NSDate() fixdate = NSCalendar.currentCalendar().dateFromComponents(datecomponent)! notification.fireDate = fixdate notification.alertTitle = "Title" notification.alertBody = "Body" UIApplication.sharedApplication().scheduleLocalNotification(notification)' 
0
source share

This is the easiest way to add a notification at a specific time, and is based on Apple developer documentation: https://developer.apple.com/documentation/usernotifications

Here is my implementation in a modular function:

 public func simpleAddNotification(hour: Int, minute: Int, identifier: String, title: String, body: String) { // Initialize User Notification Center Object let center = UNUserNotificationCenter.current() // The content of the Notification let content = UNMutableNotificationContent() content.title = title content.body = body content.sound = .default // The selected time to notify the user var dateComponents = DateComponents() dateComponents.calendar = Calendar.current dateComponents.hour = hour dateComponents.minute = minute // The time/repeat trigger let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) // Initializing the Notification Request object to add to the Notification Center let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) // Adding the notification to the center center.add(request) { (error) in if (error) != nil { print(error!.localizedDescription) } } } 
0
source share

All Articles