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

时间:2017-04-14 05:53:40

标签: ios swift time timer uilocalnotification

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

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

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

5 个答案:

答案 0 :(得分:54)

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

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

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

框架使用布尔值调用完成处理程序,指示是否已授予访问权限,如果未发生错误,则调用错误对象为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:包含警报主要原因的字符串。

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

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

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

声音:发出警报时播放的声音。使用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);
  }
  }];

答案 1 :(得分:6)

要在代码下方启动特定时间的通知。

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

并且在特定时间间隔内持续发射,例如每2分钟后使用以下线进行触发。

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 120, repeats: true)

答案 2 :(得分:2)

对于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
        }
    })

希望得到这个帮助。

答案 3 :(得分:0)

试试这个

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

答案 4 :(得分:0)

这是在特定时间添加通知的最简单方法,它基于Apple的开发人员文档:https://developer.apple.com/documentation/usernotifications

这是我在模块化函数中的实现:

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