我最近将我的项目更新为IOS 10,这导致我注册的任何本地通知都没有触发。我试图将本地通知转换为用户通知,但它没有相同的效果。这是我试图转换的原始代码。在viewDidLoad中:
guard let settings = UIApplication.shared.currentUserNotificationSettings else { return
}
if settings.types == UIUserNotificationType() {
let ac = UIAlertController(title: "Cant Schedule", message: "No Permission", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(ac, animated: true, completion: nil)
return
}
var dateComp: DateComponents = DateComponents()
dateComp.year = 2017;
dateComp.month = 01;
dateComp.day = 28;
dateComp.hour = 11;
dateComp.minute = 0;
(dateComp as NSDateComponents).timeZone = TimeZone.current
let calender:Calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let date:Date = calender.date(from: dateComp)!
let notification = UILocalNotification()
notification.fireDate = date
notification.alertBody = "Notification!"
notification.alertAction = "You just Received a notification!"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = ["customField1": "w00t"]
notification.repeatInterval = NSCalendar.Unit.weekOfYear
UIApplication.shared.scheduleLocalNotification(notification)
这导致当地通知在每个星期六上午11点开火。
以下是我在IOS 10中尝试实现相同效果的代码:
func scheduleNotification(at date: Date) {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(in: .current, from: date)
let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)
let content = UNMutableNotificationContent()
content.title = "Notification"
content.body = "You just Received a notification!"
content.sound = UNNotificationSound.default()
let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Error")
}
}
}
在viewDidLoad中:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) {(accepted, error) in
if !accepted {
print("Error")
}
}
如果用户使用datePicker选择日期,此代码可以正常工作,但我无法弄清楚如何以通过编程方式将通知日期设置为我在本地通知中的相同日期(2017-28-01 11 :00),以及如何在没有repeatInterval属性的同时每周触发通知。
答案 0 :(得分:1)
你能解释一下你如何只能在周一上午11点指定
这只是遗漏了不适用于重复值的所有事情。因此,在您的情况下,您希望指定日期组件hour:11
和weekday:2
,而不是其他任何内容。
要了解其工作原理,请在操场上运行:
let dc = DateComponents(hour:11, weekday:2)
let greg = Calendar(identifier: .gregorian)
let d = greg.nextDate(after: Date(), matching: dc, matchingPolicy:.nextTime)
你会看到d
是星期一上午11点。
这正是UNNotificationTrigger将要确定何时发送此通知的行为。
现在,如果您还将此设置为repeats
触发器,则您刚刚在上午11点指定每个星期一。