![](/img/trans.png)
[英]Swift: Creating a repeating local notification between a set time each day
[英]Repeating local notification daily at a set time with swift
我是iOS開發的新手,但已經創建了應用程序,我正在嘗試創建一段時間的每日通知。 目前,通知對於給定的日期/時間執行一次。 我不確定如何使用repeatInterval方法每天安排它。 每天重復通知的最佳方法是什么? 任何幫助將不勝感激(Y)。
var dateComp:NSDateComponents = NSDateComponents()
dateComp.year = 2015;
dateComp.month = 06;
dateComp.day = 03;
dateComp.hour = 12;
dateComp.minute = 55;
dateComp.timeZone = NSTimeZone.systemTimeZone()
var calender:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
var date:NSDate = calender.dateFromComponents(dateComp)!
var notification:UILocalNotification = UILocalNotification()
notification.category = "Daily Quote"
notification.alertBody = quoteBook.randomQuote()
notification.fireDate = date
notification.repeatInterval =
UIApplication.sharedApplication().scheduleLocalNotification(notification)
您必須提供NSCalendarUnit值,如“HourCalendarUnit”或“DayCalendarUnit”,以重復通知。
只需添加此代碼即可每天重復本地通知:
notification.repeatInterval = NSCalendarUnit.CalendarUnitDay
所以,不得不修改@ vizllx上面的代碼。 這是新行:
notification.repeatInterval = NSCalendarUnit.Day
這是我使用的完整工作示例:
let notification = UILocalNotification()
/* Time and timezone settings */
notification.fireDate = NSDate(timeIntervalSinceNow: 8.0)
notification.repeatInterval = NSCalendarUnit.Day
notification.timeZone = NSCalendar.currentCalendar().timeZone
notification.alertBody = "A new item is downloaded."
/* Action settings */
notification.hasAction = true
notification.alertAction = "View"
/* Badge settings */
notification.applicationIconBadgeNumber =
UIApplication.sharedApplication().applicationIconBadgeNumber + 1
/* Additional information, user info */
notification.userInfo = [
"Key 1" : "Value 1",
"Key 2" : "Value 2"
]
/* Schedule the notification */
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
var repeatInterval: NSCalendarUnit
=>文檔說“重新安排通知的日歷間隔”。
所以:使用NSCalendarUnit.CalendarUnitDay
其他答案顯示了如何使用舊的iOS 10之前的本地通知。 對於iOS 10及更高版本,您必須使用UNNotificationCenter,如下所示:
let content = UNMutableNotificationContent()
content.title = "This will appear in bold, on it's own line."
content.subtitle = "This will appear in bold, on it's own line, below the title."
content.body = "This will appear as normal text, below the title and subtitle."
let triggerInputForHourlyRepeat = Calendar.current.dateComponents([.minute], from: intendedFireDateVariable)
let trigger = UNCalendarNotificationTrigger.init(dateMatching: triggerInput, repeats: true)
let request = UNNotificationRequest(identifier: "someUniqueID", content: content, trigger: trigger)
let unc = UNUserNotificationCenter.current()
unc.add(request, withCompletionHandler: { (error) in
/// Handle error
})
有用的教程:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.