在 iOS 中的特定时间启动本地通知
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43405959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Launch a local notification at a specific time in iOS
提问by imjonu
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.
我正在尝试创建一个计时器,它会在用户设置的时间触发本地通知。我遇到的问题是我无法找到一种方法来设置本地通知在晚上 7:00 关闭。在研究这个问题时发现的几乎所有方法都涉及从当前日期开始的某个时间段内发出的本地通知。我试图让用户选择晚上 7:00,然后在那个时候关闭通知。从逻辑上讲,这可以通过拥有最终时间(用户选择的值)来实现 - 当前时间将为您提供时差。然而,我不完全确定如何做到这一点。
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
回答by Vikram Sahu
Well in iOS 10 Apple has deprecated UILocalNotification which means it is time to get familiar with a new notifications framework.
好吧,在 iOS 10 中,Apple 已弃用 UILocalNotification,这意味着是时候熟悉新的通知框架了。
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:
您通过共享的 UNUserNotificationCenter 对象管理通知:
// 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:
授权与旧的通知框架一样,您需要获得用户对应用程序将使用的通知类型的许可。在应用程序生命周期的早期发出请求,例如在application:didFinishLaunchingWithOptions: 中。您的应用程序第一次请求授权时,系统会向用户显示警报,之后他们可以从设置中管理权限:
// 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.
框架使用一个布尔值调用完成处理程序,指示是否授予访问权限,如果没有发生错误,则该错误对象将为 nil。
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:
注意:用户可以随时更改您的应用程序的通知设置。您可以使用 getNotificationSettings 检查允许的设置。这与 UNNotificationSettings 对象异步调用完成块,您可以使用它来检查授权状态或单个通知设置:
// 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:
创建通知请求 UNNotificationRequest 通知请求包含内容和触发条件:
Notification Content
通知内容
The content of a notification is an instance of the UNMutableNotificationContent with the following properties set as required:
通知的内容是 UNMutableNotificationContent 的一个实例,根据需要设置了以下属性:
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.
sound:发出警报时播放的声音。使用 UNNotificationSound.default() 或从文件创建自定义声音。launchImageName:如果您的应用程序响应通知而启动时要使用的启动图像的名称。
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.
userInfo:要传入通知附件的自定义信息字典:UNNotificationAttachment 对象数组。用于包含音频、图像或视频内容。
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.
请注意,在对标题等警报字符串进行本地化时,最好使用 localizedUserNotificationString(forKey:arguments:),这会延迟加载本地化,直到传递通知。
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);
}
}];
回答by Parth Barot
To launch notification on specific time use below code.
要在特定时间启动通知,请使用以下代码。
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 launch constantly in specific time interval for example after every 2 minutes use below line for trigger.
并在特定的时间间隔内不断启动,例如每 2 分钟后使用线下触发。
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 120, repeats: true)
回答by Abhirajsinh Thakore
For Swift You can possibly Use this Code:
对于 Swift,您可以使用以下代码:
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 Help.
希望这有帮助。
回答by Caleb Hensley
This is the simplest way to add a notification at a specific time, and it is based off of Apple's Developer Documentation: https://developer.apple.com/documentation/usernotifications
这是在特定时间添加通知的最简单方法,它基于 Apple 的开发人员文档: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)
}
}
}
回答by shirish
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)`