Setting UserNotification with date from a realm database swift

余生颓废 提交于 2019-12-13 03:52:44

问题


I am trying to create a notification based on date and time specified by a user for an application I am working on. I am able to save user's date and retrieve. I now want a notification to pop up when the user's specified date has arrived just like an reminder thing. I can create a notification with with hard coded values but now retriving from the Real database to pass into the trigger value is what I am unable to do. my codes are specified below

func notifcation() -> Void {

        let calendar = Calendar.current
        let components = DateComponents(year: 2018, month: 09, day: 08, hour: 18, minute: 55) // Set the date here when you want Notification
        let date = calendar.date(from: components)
        let comp2 = calendar.dateComponents([.year,.month,.day,.hour,.minute], from: date!)
        let trigger = UNCalendarNotificationTrigger(dateMatching: comp2, repeats: true)
        let content = UNMutableNotificationContent()
        content.title = "Don't forget"
        content.body = "Buy some milk"
        content.sound = UNNotificationSound.default()
        let identifier = "UYLLocalNotification"
        let request = UNNotificationRequest(identifier: identifier,
                                            content: content, trigger: trigger)

        center.add(request, withCompletionHandler: { (error) in
            if let error = error {
                // Something went wrong
                print(error as Any)
            }
        })
    }

then I call notification() in my viewDidLoad

Model

class ListModel: Object {
    @objc dynamic var createdDate: Date?
    @objc dynamic var remiderDate: Date?
}

based on Sh answer My function

func getDataFromDB() -> Results<ListModel>? {
        let todoListArray: Results<ListModel> = database.objects(ListModel.self)
        return todoListArray
    }

my viewdidLoad was now

TodoListFunctions.instance.getDataFromDB()?.forEach({ (list) in

            notifcation(list.remiderDate)
        })

in my AppDelegate for Permission

let center = UNUserNotificationCenter.current()
        let options: UNAuthorizationOptions = [.alert, .sound]

        center.requestAuthorization(options: options) {
            (granted, error) in
            if !granted {
                print("Something went wrong")
            }
        }

further codes would be supplied on request


回答1:


You can try

let allList = self.database.objects(ListModel.self)
allList.forEach{ notifcation($0.remiderDate) }

//

func notifcation(_ reminder:Date?) -> Void { 

        guard let date = reminder else { return }
        let comp2 = calendar.dateComponents([.year,.month,.day,.hour,.minute], from: date)
        let trigger = UNCalendarNotificationTrigger(dateMatching: comp2, repeats: true)
        let content = UNMutableNotificationContent()
        content.title = "Don't forget"
        content.body = "Buy some milk"
        content.sound = UNNotificationSound.default()
        let identifier = "\(date)"  // identider should be different for each one 
        let request = UNNotificationRequest(identifier: identifier,
                                            content: content, trigger: trigger)

        center.add(request, withCompletionHandler: { (error) in
            if let error = error {
                // Something went wrong
                print(error as Any)
            }
        })
    }

//

Set the delegate inside AppDelegte

UNUserNotificationCenter.current().delegate = self

and notice the print from

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert, .sound])
}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  print("notification received")
}


来源:https://stackoverflow.com/questions/52238005/setting-usernotification-with-date-from-a-realm-database-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!