如何在iOS 10中更新每日本地通知消息?

时间:2017-04-12 05:07:01

标签: ios swift swift3 unusernotificationcenter

我试图了解如何在每天重复的情况下更新本地通知中的邮件。

目前我的AppDelegate中有以下代码:

func scheduler(at date: Date, numOfNotes: Int)
{
    let calendar = Calendar(identifier: .gregorian)

    let components = calendar.dateComponents(in: .current, from: date)

    let newComponents = DateComponents(calendar: calendar, timeZone: .current, hour: components.hour, minute: components.minute)

    let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)

    content.badge = numOfNotes as NSNumber

    content.body = "REMINDER: " + String(numOfNotes) + " needs to be looked at!"

    content.sound = UNNotificationSound.default()

    let request = UNNotificationRequest(identifier: "reminderNotification", content: content, trigger: trigger)

    UNUserNotificationCenter.current().delegate = self

    UNUserNotificationCenter.current().add(request) {(error) in

    }
}

我将numOfNotes存储在UserDefaults中。我的UISwitch中有一个UITableViewCell,在启动时会调用scheduler函数,如下所示:

func remindMeSwitch(_ remindMeSwitch: UISwitch)
{   
    numOfNotes = UserDefaults.standard.integer(forKey: "Notes")

    let delegate = UIApplication.shared.delegate as? AppDelegate

    delegate?.scheduler(at: time, numOfNotes: numOfNotes)
}

但是,在将repeats参数设置为true以使通知在指定时间每天重复时,numOfNotes仅被调用一次,这是我切换{{1在...上。

如何将通知设置为每日提醒,但仍然可以根据需要更新通知消息?

感谢。

1 个答案:

答案 0 :(得分:0)

通常,您无法更改本地通知。 只有一种方法 - 删除/取消旧通知并创建新通知。但是你可以使用复制功能。

例如,如果您想更改通知的内容:

// create new content (based on old)
if let content = notificationRequest.content.mutableCopy() as? UNMutableNotificationContent {
    // any changes    
    content.title = "your new content's title"
    // create new notification
    let request = UNNotificationRequest(identifier: notificationRequest.identifier, content: content, trigger: notificationRequest.trigger)
    UNUserNotificationCenter.current().add(request)
}