Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 views
in Technique[技术] by (71.8m points)

swift - Launch a local notification at a specific time in iOS

I am trying to create a timer which triggers a local notification to go off at a time that the user has set. The issue I am having is that I cannot figure out a way to be able to set the local notification to go off at say 7:00PM. Almost all the methods found when researching this issue involved the local notification going off at a certain amount of time from the current date. I am trying to allow the user to select 7:00PM and then have the notification go off at that time. Logically it makes sense that this can be achieved through having the final time (selected value by the user) - current time which would give you the time difference. I am however not entirely sure how to do this.

Any help with regard to the topic will be very much appreciated, thank you. Below is the code which I am currently using 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well in iOS 10 Apple has deprecated UILocalNotification which means it is time to get familiar with a new notifications framework.

Setup This is a long post so let’s start easy by importing the new notifications framework:

// Swift
import UserNotifications

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

You manage notifications through a shared UNUserNotificationCenter object:

// Swift
let center = UNUserNotificationCenter.current()

// Objective-C
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

Authorization As with the older notifications framework you need to have the user’s permission for the types of notification your App will use. Make the request early in your App life cycle such as in application:didFinishLaunchingWithOptions:. The first time your App requests authorization the system shows the user an alert, after that they can manage the permissions from settings:

// Swift
let options: UNAuthorizationOptions = [.alert, .sound];

// Objective-C
UNAuthorizationOptions options = UNAuthorizationOptionAlert + UNAuthorizationOptionSound;

You make the actual authorization request using the shared 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 framework calls the completion handler with a boolean indicating if the access was granted and an error object which will be nil if no error occurred.

Note: The user can change the notifications settings for your App at any time. You can check the allowed settings with getNotificationSettings. This calls a completion block asynchronously with a UNNotificationSettings object you can use to check the authorization status or the 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 A UNNotificationRequest notification request contains content and a trigger condition:

Notification Content

The content of a notification is an instance of the UNMutableNotificationContent with the following properties set as required:

title: String containing the primary reason for the alert.

subtitle: String containing an alert subtitle (if required)

body: String containing the alert message text

badge: Number to show on the app’s icon.

sound: A sound to play when the alert is delivered. Use UNNotificationSound.default() or create a custom sound from a file. launchImageName: name of a launch image to use if your app is launched in response to a notification.

userInfo: A dictionary of custom info to pass in the notification attachments: An array of UNNotificationAttachment objects. Use to include audio, image or video content.

Note that when localizing the alert strings like the title it is better to use localizedUserNotificationString(forKey:arguments:) which delays loading the localization until the notification is delivered.

A 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 Trigger

Trigger a notification based on time, calendar or location. The trigger can be repeating:

Time interval: Schedule a notification for a number of seconds later. For example to trigger in five minutes:

 // Swift
 let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 300, repeats: false)

 // Objective-C
 UNTimeIntervalNotificationTrigger *trigger =     [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:300
                              repeats:NO];

Calendar: Trigger at a specific date and time. The trigger is created using a date components object which makes it easier for certain repeating 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 the trigger from the 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 certain interval use the correct set of date components. For example, to have the notification repeat daily at the same time we need just the hour, minutes and seconds:

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

To have it repeat weekly at the same time we also need the weekday:

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

Scheduling

With both the content and trigger ready we create a new notification request and add it to the notification center. Each notification request requires a string identifier 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);
  }
  }];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...