首页 > 解决方案 > 如何创建不必在 Apple 的提醒应用中显示的提醒

问题描述

使用以下代码,我可以成功创建提醒事件并向其添加警报,该警报在事件创建后 10 秒触发。我不喜欢创建提醒的方式是它显示在 Apple 的提醒应用程序中,当您在设备中收到通知消息时,它会显示提醒的应用程序图标。

是否可以将提醒设为私密,使其不会显示在 Apple 的提醒应用中?如果没有,我有什么选择来完成这样的任务?

注意:我不介意将提醒存储在标准提醒本地数据库中,只要它们不显示在默认提醒应用程序中即可。

import EventKit

class ViewController: UIViewController{
    var eventStore = EKEventStore()

    override func viewDidLoad(){
        super.viewDidLoad()
        // get user permission
        eventStore.requestAccess(to: EKEntityType.reminder, completion: {(granted, error) in
            if !granted{
                print("Access denied!")
            }
        })
    }

    @IBAction func createReminder(_ sender: Any) {
        let reminder = EKReminder(eventStore: self.eventStore)
        reminder.title = "Get Milk from the Store"
        reminder.calendar = eventStore.defaultCalendarForNewReminders()
        let date = Date()
        let alarm = AKAlarm (absoluteDate: date.addingTimeInterval(10) as Date)
        reminder.addAlarm(alarm)

        do {
            try eventStore.save(reminder, commit: true)
        } catch let error {
            print("Error: \(error.localizedDescription)")
        }
    }
}

仅供参考 - 要使上述代码正常工作,您需要NSRemindersUsageDescription在 info.plist 文件中添加密钥。

标签: iosswifteventkitreminders

解决方案


只是为了记录,这正是我想要的。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
        if granted{
            print("User gave permissions for local notifications")
        }else{
            print("User did NOT give permissions for local notifications")
        }
    }
    return true
}


 override func viewDidLoad() {
    super.viewDidLoad()
    setReminderAtTime()
} 

func setReminderAtTime(){
    let reminderTime:TimeInterval = 60

    let center = UNUserNotificationCenter.current()
    center.removeAllPendingNotificationRequests()
    
    let content =  UNMutableNotificationContent()
    content.title = "Title"
    content.body = "Notification Message!."
    content.sound = .default
    
    let trigger =  UNTimeIntervalNotificationTrigger(timeInterval: reminderTime, repeats: false)
    let request = UNNotificationRequest(identifier: "reminderName", content: content, trigger: trigger)
    
    center.add(request) { (error) in
        if error != nil{
            print("Error = \(error?.localizedDescription ?? "error local notification")")
        }
    }
}

推荐阅读