我正在为我的应用程序使用 localNotifications。我有一个日期选择器,用户可以从中选择通知的日期和时间,我还有 3 个分段控件(每天、每周、每月)。我已经完成了 localnotification 及其编码工作。但是分段控制不起作用,如果一个人选择两次(下午 1 点)和第二次(下午 2 点),然后通知在我不想要的两个时间显示。下面是代码
在 appdelegate.swift 中
let types:UIUserNotificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
let myAlarmSetting:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: categories as Set<NSObject>)
UIApplication.sharedApplication().registerUserNotificationSettings(myAlarmSetting)
在 notifications.swift 中 @IBAction func NotificationButtonTapped(sender: AnyObject) {
var notifications:UILocalNotification = UILocalNotification()
notifications.fireDate = datePicker.date
notifications.timeZone = NSTimeZone.defaultTimeZone()
notifications.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
notifications.soundName = UILocalNotificationDefaultSoundName
switch(frequencysegmentedcontrol.selectedSegmentIndex){
case 0:
notifications.repeatInterval = NSCalendarUnit.CalendarUnitDay
break;
case 1:
notifications.repeatInterval = NSCalendarUnit.CalendarUnitWeekOfYear
break;
case 2:
notifications.repeatInterval = NSCalendarUnit.CalendarUnitYear
break;
default:
notifications.repeatInterval = NSCalendarUnit(0)
break;
}
notifications.alertBody = "quote of the day"
notifications.category = "First_category"
UIApplication.sharedApplication().scheduleLocalNotification(notifications)
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
application.applicationIconBadgeNumber = 0
}
最佳答案
我可以帮助您解决两次本地通知问题。
解决方案:
问题是当您添加任何本地通知时 - 首先您需要检查是否安排了任何本地通知?
So, how we can check?
那么,您需要在 notifications.userInfo
中存储一些数据。
例如
var userInfo = [String:String]()
let example = "SomeNotification"
userInfo["example"] = example
notification.userInfo = userInfo
引用:https://www.hackingwithswift.com/read/21/2/scheduling-notifications-uilocalnotification
因此,一旦您更新同一通知的时间,您需要取消现有通知并使用新时间设置新通知。
var app:UIApplication = UIApplication.sharedApplication()
for oneEvent in app.scheduledLocalNotifications {
var notification = oneEvent as UILocalNotification
let userInfoCurrent = notification.userInfo! as [String:AnyObject]
let uid = userInfoCurrent["uid"]! as String
if uid == uidtodelete {
//Cancelling local notification
app.cancelLocalNotification(notification)
break;
}
}
关于xcode - DatePicker 本地通知(Xcode,swift2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31870193/