在iOS的特定时间启动本地通知

我正在尝试创build一个计时器,触发本地通知在用户设置的时间closures。 我遇到的问题是我无法想出一个办法,可以设置本地通知在下午7:00点closures。 在研究这个问题时,几乎所有的方法都是在当地通知从当前date起的一定时间内发生的。 我正在尝试让用户select晚上7点,然后在那个时候通知。 从逻辑上讲,通过获得最后的时间(用户select的值)可以实现这一点 – 当前的时间会给你时间差。 但我不完全确定如何做到这一点。

对这个话题的任何帮助将非常感谢,谢谢。 以下是我目前用来触发本地通知的代码。

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中,苹果已经弃用了UILocalNotification,这意味着是时候熟悉一个新的通知框架了。

安装这是一个很长的文章,让我们从导入新的通知框架开始:

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

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

 // Swift let center = UNUserNotificationCenter.current() // Objective-C UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; 

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

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

框架用布尔值调用完成处理程序,指示访问是否被授予,如果没有错误发生,错误对象将为零。

注意:用户可以随时更改您的应用程序的通知设置。 您可以使用getNotificationSettings检查允许的设置。 这会使用UNNotificationSettings对象asynchronous调用完成块,您可以使用该对象检查授权状态或单个通知设置:

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

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

通知内容

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

title:包含警报主要原因的string。

字幕:包含警告字幕的string(如果需要)

body:包含警报消息文本的string

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

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

userInfo:要传递通知附件的自定义信息字典:UNNotificationAttachment对象数组。 用于包含audio,图像或video内容。

请注意,在本地化警报string(如标题)时,最好使用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]; 

日历:在特定date和时间触发。 触发器是使用date组件对象创build的,这使得某些重复间隔更容易。 要将date转换为date组件,请使用当前日历。 例如:

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

从date组件创build触发器:

  // Swift let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false) // Objective-C UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:triggerDate repeats:NO]; 

要创build以特定间隔重复的触发器,请使用正确的date组件组。 例如,要每天重复通知,我们只需要小时,分钟和秒钟:

  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) 

调度

随着内容和触发器准备就绪,我们创build一个新的通知请求,并将其添加到通知中心。 每个通知请求都需要一个string标识符供将来参考

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

尝试这个

  ` 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)`