DatePicker 本地通知(Xcode,swift2)

DatePicker Local Notification(Xcode,swift2)

我正在为我的 app.I 使用 localNotifications,它有一个日期选择器,用户可以从中选择通知的日期和时间,我还有 3 个分段控件(每天、每周、每月)。我已经完成了编码对于 localnotification 及其 working.But,分段控制不起作用,如果一个人选择两次,比如一次(下午 1 点)和第二次(下午 2 点),然后通知在我不显示的两个时间显示want.Below是代码

在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(发件人: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;
    }
}

参考:Delete a particular local notification