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

标签 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 中。我的 UITableViewCell 中有一个 UISwitch,打开后会调用 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 仅被调用一次,这是我打开 UISwitch 的时间。

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

谢谢。

最佳答案

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

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

// 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)
}

关于ios - 如何在iOS 10中更新每日本地通知消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43360706/

相关文章:

swift - 如何使用 SKAction 改变 SKSpriteNode 的位置

ios - 我如何使用 Swift 3 发出 HTTP 请求?

swift - 为什么过滤裁剪图像比过滤调整大小的图像慢 4 倍(两者具有相同的尺寸)

iphone - 如何在xcode上创建电子邮件表单?

ios - Swift TouchBegan 导致 Xcode 崩溃,同时仍在 TouchEnded 中执行功能

xml - 使用 Swift 3 pretty-print XML

swift - 我如何将承认插页式广告集成到 swift 3 中。它是一个虚拟按钮

ios - 在 Tableview 中偏移 HeaderView 以显示类似卡片

ios - Swift segue过渡阴影

iphone - 比较两个 NSDate 失败