Search code examples
iospush-notificationswift3push

How to get a push notification at a set time? (Swift 3)


I'm making an app that's supposed the user everyday at a set time about the news. It get's the text of the news through a function which calls it from an array. My question is: how do I get my app to call the function and then send me a push notification with the info text every day at, let's say, 4am?

Thanks to everyone for answering! Have a great day!


Solution

  • Here is some code I used before. Not a hundred-percent what you are looking for, but I hope useful for you.

    You need to modify it to be sending daily

    import UIKit
    import UserNotifications
     
    class ViewController: UIViewController, UNUserNotificationCenterDelegate {
        var isGrantedNotificationAccess:Bool = false
        @IBAction func send10SecNotification(_ sender: UIButton) {
            if isGrantedNotificationAccess {
                //add notification code here
             
                //Set the content of the notification
                let content = UNMutableNotificationContent()
                content.title = "10 Second Notification Demo"
                content.subtitle = "From MakeAppPie.com"
                content.body = "Notification after 10 seconds - Your pizza is Ready!!"
             
                //Set the trigger of the notification -- here a timer. 
                let trigger = UNTimeIntervalNotificationTrigger(
                    timeInterval: 10.0,
                    repeats: true)
             
                //Set the request for the notification from the above
                let request = UNNotificationRequest(
                    identifier: "10.second.message",
                    content: content,
                    trigger: trigger
                )
             
                //Add the notification to the currnet notification center
                UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
             
            }
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (granted, error) in
                self.isGrantedNotificationAccess = granted
            }
        }
    }