"稍后提醒我"本地通知的功能

时间:2017-04-20 15:35:53

标签: ios swift notifications

我希望通过添加"稍后提醒我"来扩展我的本地通知功能。行动。换句话说,如果用户点击"稍后提醒我"我想在一段时间后重新发出通知。按钮。

即使所有内容都应该在我的应用中正确连接(检查通知是否已启用,设置通知类别和委托,处理提醒我以后的功能),在点击提醒稍后按钮后安排的通知不显示在所有

设置所有内容(检查权限,设置类别)

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) {(accepted, error) in
        if !accepted {
            print("Notification access denied.")
        }
    }

    let action = UNNotificationAction(identifier: "remindLater", title: "Remind me later", options: [])
    let category = UNNotificationCategory(identifier: "myCategory", actions: [action], intentIdentifiers: [], options: [])
    UNUserNotificationCenter.current().setNotificationCategories([category])

    return true
}

处理点击"稍后提醒我"

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    if response.actionIdentifier == "remindLater" {
        let newDate = Date(timeInterval: 10, since: Date())
        scheduleNotification(at: newDate, withCompletionHandler: { 
            completionHandler()
        })
    }
}

设置本地通知的实际代码:

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: false)

    let content = UNMutableNotificationContent()
    content.title = "Tutorial Reminder"
    content.body = "Just a reminder to read your tutorial over at appcoda.com!"
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier = "myCategory"

    let request = UNNotificationRequest(identifier: date.description, content: content, trigger: trigger)

    UNUserNotificationCenter.current().delegate = self
    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    UNUserNotificationCenter.current().add(request) {(error) in
        if let error = error {
            print("Uh oh! We had an error: \(error)")
        }
    }
}

我做错了什么? I am using AppCoda iOS 10 user notifications guide.this is the sample code

1 个答案:

答案 0 :(得分:2)

问题是您需要为正在安排的每个通知使用唯一标识符。您可以使用触发日期说明。不要忘记您需要关闭应用才能收到通知。