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

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

问题描述

我正在尝试创建一个计时器,它会在用户设置的时间触发本地通知.我遇到的问题是我无法找到一种方法来设置本地通知在晚上 7:00 关闭.在研究这个问题时发现的几乎所有方法都涉及从当前日期开始的特定时间段内发出的本地通知.我试图让用户选择晚上 7:00,然后在那个时候关闭通知.从逻辑上讲,这可以通过拥有最终时间(用户选择的值)来实现 - 当前时间将为您提供时差.然而,我不完全确定如何做到这一点.

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

推荐答案

Apple 在 iOS 10 中弃用了 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.

sound:发出警报时播放的声音.使用 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天全站免登陆