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

非常感谢您对该主题的任何帮助。以下是我当前用于触发本地通知的代码。

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,这意味着该是时候熟悉一个新的通知框架了。

设置
这是一篇很长的文章,所以让我们通过导入新的通知框架来轻松开始:

// Swift
import UserNotifications

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

您可以通过共享的UNUserNotificationCenter对象管理通知:
// Swift
let center = UNUserNotificationCenter.current()

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

授权
与旧的通知框架一样,您需要获得用户对您的应用将使用的通知类型的许可。在您的应用生命周期中尽早发出请求,例如 application:didFinishLaunchingWithOptions:。 ,当您的应用第一次请求授权时,系统会向用户显示警报,然后他们可以通过设置管理权限:
// Swift
let options: UNAuthorizationOptions = [.alert, .sound];

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

您可以使用共享的通知中心发出实际的授权请求:
// 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");
}
}];

框架使用一个 bool 值(称为 bool 值)来指示完成处理程序,该 bool 值指示是否已授予访问权限,如果错误未发生,则该错误对象将为nil。

注意:用户可以随时更改您的应用程序的通知设置。您可以使用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
 }
 }];

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

通知内容

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

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

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

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

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

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

userInfo:传入通知的自定义信息字典
附件:UNNotificationAttachment对象的数组。用于包含音频,图像或视频内容。

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

一个简单的例子:
 // 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];

通知触发

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

时间间隔:将通知安排在几秒钟后。例如要在五分钟内触发:
 // Swift
 let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 300, repeats: false)

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

日历:在特定的日期和时间触发。触发器是使用日期组件对象创建的,该对象使某些重复间隔变得更容易。要将日期转换为其日期成分,请使用当前日历。例如:
 // 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];

要从日期组件创建触发器,请执行以下操作:
 // Swift
 let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)

 // Objective-C
 UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:triggerDate
                                     repeats:NO];

若要创建以一定间隔重复的触发器,请使用正确的日期组件集。例如,要使通知每天重复一次,我们只需要小时,分钟和秒:
 let triggerDaily = Calendar.current.dateComponents([hour, .minute, .second], from: date)
 let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)

为了使它每周一次重复,我们还需要一个工作日:
 let triggerWeekly = Calendar.current.dateComponents([.weekday, .hour, .minute, .second], from: date)
 let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)

安排

在内容和触发器都准备就绪的情况下,我们创建一个新的通知请求并将其添加到通知中心。每个通知请求都需要一个字符串标识符以供将来引用:
 // 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 - 在iOS的特定时间启动本地通知,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43405959/

10-17 02:20