在iOS的特定时间启动本地通知 [英] Launch a local notification at a specific time in iOS

查看:145
本文介绍了在iOS的特定时间启动本地通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个计时器,该计时器在用户设置好时间后触发本地通知.我遇到的问题是我无法找到一种方法来将本地通知设置为在晚上7:00发出.研究此问题时发现的几乎所有方法都涉及从当前日期起在一定时间范围内关闭本地通知.我正在尝试允许用户选择7:00 PM,然后在该时间关闭通知.从逻辑上讲,这可以通过设置最终时间(用户选择的值)-当前时间来实现,这将为您带来时差.但是,我不确定如何做到这一点.

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

推荐答案

在iOS 10中,Apple已弃用UILocalNotification,这意味着该是时候熟悉一个新的通知框架了.

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;

您可以通过共享的UNUserNotificationCenter对象管理通知:

You manage notifications through a shared UNUserNotificationCenter object:

// Swift
let center = UNUserNotificationCenter.current()

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

授权 与旧的通知框架一样,您需要获得用户对您的应用将使用的通知类型的许可.在您的应用生命周期中尽早发出请求,例如在 application:didFinishLaunchingWithOptions:.中.您的应用首次请求授权时,系统会向用户显示警报,之后他们可以通过设置来管理权限:

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");
}
}];

该框架使用一个布尔值调用完成处理程序,该布尔值指示是否已授予访问权限,如果错误未发生,则该错误对象将为nil.

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.

注意:用户可以随时更改您的应用程序的通知设置.您可以使用getNotificationSettings检查允许的设置.这将与UNNotificationSettings对象异步调用完成块,可用于检查授权状态或各个通知设置:

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
 }
 }];

创建通知请求 UNNotificationRequest通知请求包含内容和触发条件:

Creating A Notification Request A UNNotificationRequest notification request contains content and a trigger condition:

通知内容

通知的内容是UNMutableNotificationContent的实例,并根据需要设置以下属性:

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

title:包含警报的主要原因的字符串.

title: String containing the primary reason for the alert.

subtitle:包含警报字幕的字符串(如果需要)

subtitle: String containing an alert subtitle (if required)

body:包含警报消息文本的字符串

body: String containing the alert message text

徽章:显示在应用程序图标上的数字.

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

声音:警报发出时播放的声音.使用UNNotificationSound.default()或从文件创建自定义声音. launchImageName:如果启动应用程序以响应通知,则使用的启动图像的名称.

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:传入通知的自定义信息字典 附件:UNNotificationAttachment对象的数组.用于包含音频,图像或视频内容.

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.

请注意,在对警报字符串(如标题)进行本地化时,最好使用localizedUserNotificationString(forKey:arguments :),这会延迟本地化的加载,直到传递通知为止.

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.

一个简单的例子:

 // 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];

通知触发器

根据时间,日历或位置触发通知.触发可以重复:

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)

计划

在内容和触发器都准备就绪的情况下,我们创建一个新的通知请求并将其添加到通知中心.每个通知请求都需要一个字符串标识符以供将来参考:

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);
  }
  }];

这篇关于在iOS的特定时间启动本地通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆