我最近更新了我的项目到IOS 10,导致我注册的任何本地通知不会触发。我试图将本地通知转换为用户通知,但它不具有相同的效果。这是我尝试转换的原始代码。在viewDidLoad:Swift:将本地通知转换为用户通知IOS 10
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属性。
“如何使通知每周都在同一时间触发”:http://stackoverflow.com/a/40856269/341994 – matt
谢谢。你能解释一下,你只能在星期一上午11点指定吗?我不太明白你如何只将这些信息输入到变量中。 –
带小时11和工作日的日期组件2 – matt