noobprogrammer
noobprogrammer

Reputation: 345

How to fire a notification X minutes from now?

I want to be able to hit a button that says "1 minute from now" or "1 hour from now" and have a notification go off (push / banner). How do I go about doing this?

Upvotes: 0

Views: 136

Answers (2)

Chengappa C D
Chengappa C D

Reputation: 1891

Here you go, have written code to schedule local notification :

//First register for User Settings if iOS8 or above
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
...
     if #available(iOS 8, *) {
          application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil))
     }
...
return true
}

//Function to schedule the local notification
func scheduleNotificationWithInterval(secondsAfter:Double, notificationTitle title:String, notificationBody body:String) {

     let fireDate = NSDate()

     let localNotif = UILocalNotification()

     localNotif.fireDate = fireDate.dateByAddingTimeInterval(secondsAfter)

     localNotif.alertBody = body

     if #available(iOS 8.2, *) {
          localNotif.alertTitle = title
     }

     localNotif.soundName = UILocalNotificationDefaultSoundName;
     localNotif.applicationIconBadgeNumber = 1;

     UIApplication.sharedApplication().scheduleLocalNotification(localNotif)

}

Hope it helps :]

Upvotes: 0

fahad khan
fahad khan

Reputation: 89

set your timer according to button click if 1 min or 1 hr using the following command

 NSTimer.scheduledTimerWithTimeInterval(time, target: self, selector: #selector(functionName), userInfo: nil, repeats: true)

then broadcast the notification in that function like shown below

NSNotificationCenter.defaultCenter().postNotificationName("youFunctionName", object: nil)

addobserver in viewcontroller in which you want to receive notification

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(youFunctionName), name: "youFunctionName", object: nil)

Upvotes: 1

Related Questions