Daily Local Notification In Swift iOS 9.2 - ios

Trying to send a daily local notification in swift. However it just sends every minute for some reason. I want the first notification to send 30 mins after the app is opened and then repeat this notification everyday.
in the swift fie i have the following code:
//---------Daily notification code (also add section in app delagate----------
let theDate = NSDate()
let dateComp = NSDateComponents()
dateComp.minute = 30
let cal = NSCalendar.currentCalendar()
let fireDate:NSDate = cal.dateByAddingComponents(dateComp , toDate: theDate, options: NSCalendarOptions(rawValue: 0))!
let notification:UILocalNotification = UILocalNotification()
//choosing what it says in the notification and when it fires
notification.alertBody = "Your Daily Motivation is Awaits"
notification.fireDate = fireDate
UIApplication.sharedApplication().scheduleLocalNotification(notification)
//displaying notification every day
notification.repeatInterval = NSCalendarUnit.Day
//-------------end of daily notification code---------------
in my app delegate file i have the following code:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//----------daily notification section ----------
let notiftypes:UIUserNotificationType = UIUserNotificationType.Alert.union(UIUserNotificationType.Badge).union(UIUserNotificationType.Sound)
let notifSettings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notiftypes, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notifSettings)
return true
//----------end of daily notification section-----------
}

The problem is that you are setting the repeat interval after scheduling the notification. Just set the notification property before scheduleLocalNotification and make sure you schedule it only once:
let notification = UILocalNotification()
notification.alertBody = "Your Daily Motivation is Awaits"
// You should set also the notification time zone otherwise the fire date is interpreted as an absolute GMT time
notification.timeZone = NSTimeZone.localTimeZone()
// you can simplify setting your fire date using dateByAddingTimeInterval
notification.fireDate = NSDate().dateByAddingTimeInterval(1800)
// set the notification property before scheduleLocalNotification
notification.repeatInterval = .Day
UIApplication.sharedApplication().scheduleLocalNotification(notification)
Note: UIUserNotificationType are OptionSetType structures, so you can simplify its declaration also:
let notiftypes:UIUserNotificationType = [.Alert, .Badge, .Sound]

Related

unable to receive local notification without internet iOS swift

I'm scheduling a local notification on the moment I receive a remote notification by using the below code,
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
let scheduleLocalNotification = UILocalNotification()
scheduleLocalNotification.fireDate = dateFromRemoteNotification
scheduleLocalNotification.timeZone = NSTimeZone.localTimeZone()
scheduleLocalNotification.alertBody = "Hi There!"
scheduleLocalNotification.userInfo = userInfo
UIApplication.sharedApplication().scheduleLocalNotification(scheduleLocalNotification)
completionHandler(.NewData)
}
After successfully scheduling local notification. Now, I turned off internet, I'm not receiving local notification..
Did anyone face the same issue? or Am I missing something?
For Local Notifications write this code in your appDelegate's didFinishLaunchingWithOptions :-
let notifyTypes:UIUserNotificationType = [.Alert, .Badge, .Sound]
let settings = UIUserNotificationSettings(forTypes: notifyTypes, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
// and Schedule your notifications in your controller :-
let notification:UILocalNotification = UILocalNotification()
notification.alertTitle = " "
notification.alertBody = ""
notification.fireDate = NSDate()
UIApplication.sharedApplication().scheduleLocalNotification(notification)
you are calling the push notification receive function. you have to call didReceiveNotification only.
And need to schedule local notification from your controller not in this function.
Hope this will help you.
You have to set this code on viewWillAppear or button click event.
Not on didReceiveRemoteNotification or didReceiveLocalNotification.
Try this code on viewwillAppear or button
let notification = UILocalNotification()
notification.alertBody = "Local notification text body"
notification.alertAction = "open"
notification.fireDate = NSDate(timeIntervalSinceNow: 1) // this will fire local notification just after 1 second
notification.soundName = "soundName.mp3"
UIApplication.sharedApplication().scheduleLocalNotification(notification)
Now once you receive local notification, when you tap on that, didReceiveLocalNotification method will get call in AppDelegate
If you want to fire local notification instantly(without scheduling) then you need the following code:
let locNot:UILocalNotification = UILocalNotification();
locNot.alertBody = "Here is the local notification";
UIApplication.sharedApplication().presentLocalNotificationNow(locNot);

swift iOS localNotifications

I want to set local notifications for specific times, eg : 04:30 Am Everyday, but i cant figure it out. I am new to iOS development and all localNotifications tutorials just cover fireDate = NSDate()
Thank you!
Try this code in your function you want to fire local notification:
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let date = NSDate()
let dateComponents = calendar!.components([NSCalendarUnit.Day, NSCalendarUnit.WeekOfMonth, NSCalendarUnit.Month,NSCalendarUnit.Year,NSCalendarUnit.Hour,NSCalendarUnit.Minute], fromDate:date)
dateComponents.hour = 4
dateComponents.minute = 30
let notification = UILocalNotification()
notification.alertAction = "Title"
notification.alertBody = "Fire Fire Fire :v"
notification.repeatInterval = NSCalendarUnit.WeekOfYear
notification.fireDate = calendar.dateFromComponents(dateComponents)
UIApplication.sharedApplication().scheduleLocalNotification(notification)
And remember to put this code in your AppDelegate:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Sound, .Badge, .Alert], categories: nil))
return true
}

Recurring Local Notification in iOS

I just want to ensure I understand how local notifications work. Is it true that once I run the below code one time, I'll have weekly notifications?
//Goes in AppDelegate.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//Added this for notifications.
//Without this, I don't believe the user gets the opportunity to approve notifications from the app
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
return true
}
//Goes in viewController
func weeklyNotifications () {
let localNotification = UILocalNotification()
localNotification.fireDate = NSDate(timeIntervalSinceNow: 60*60)
localNotification.alertBody = "This is the message"
localNotification.timeZone = NSTimeZone.localTimeZone()
localNotification.repeatInterval = NSCalendarUnit.WeekOfYear
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.category = "Message" //Optional
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
In other words, the result of this code is that the first time I run the app, I can execute this code and the notification will repeat every week without me running additional code?
localNotification.repeatInterval = NSCalendarUnit.WeekOfYear
Yes this will schedule local notification for every week.

Firedate Notification in swift 2

I am trying to learn Xcode and swift and I am having trouble with getting my notification to work for a simple alarm clock I am making. I used date picker and had the notification.firedate = to that. The notification comes up on the notification window but the alert window does not come up and no sound is playing.
I also asked the user to allow notifications already. Please give me some help. Thank you
AppDelegate
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes:[ .Alert, .Badge, .Sound], categories: nil))
return true
}
ViewController
#IBAction func alarmSet(sender: AnyObject) {
let alarmPicked = timePick.date
printTime(timePick.date)
self.notify(alarmPicked)
}
func notify(date: NSDate){
let calendar = NSCalendar.currentCalendar()
let comp = calendar.components([.Hour, .Minute], fromDate: date)
let notification = UILocalNotification()
notification.timeZone = NSTimeZone.localTimeZone()
notification.fireDate = calendar.dateFromComponents(comp)
notification.alertBody = "Here is the you Alarm you scheduled!"
notification.alertAction = "Dismiss"
notification.soundName = UILocalNotificationDefaultSoundName
UIApplication.sharedApplication().scheduleLocalNotification(notification)
self.navigationController?.popToRootViewControllerAnimated(true)
}
As of iOS 8+, UIApplication requires that you register your notification settings. It will let you schedule them if you don't, but they will never fire.
You register your settings like this:
let myNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(myNotificationSettings)
Then you can schedule notifications which will actually fire.
See Apple's SDK: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/IPhoneOSClientImp.html#//apple_ref/doc/uid/TP40008194-CH103-SW1

Ios local notification at same time but different alert message for different date

I want an example code for daily quote that get locAl notification for everyday of year with given different message/quote
Better would be add different UILocalNotificaitons for each day in a loop, create a reference data lets say today and then loop 365 times and add one day timeInterval in each iteration register them to app, something like this
var messages:[String] = [/*Add messages here*/]
var date = NSDate()
let dayTimerInterval:NSTimeInterval = (60 * 60 * 26)
date = date.dateByAddingTimeInterval(dayTimerInterval)
for i in 0..<messages.count
{
let localNotif = UILocalNotification()
localNotif.alertBody = messages[i]
localNotif.fireDate = date
date = date.dateByAddingTimeInterval(dayTimerInterval)
UIApplication.sharedApplication().scheduleLocalNotification(localNotif)
}
There is another way that you can do that with one notification and that when a local notification fire and user open app then you change its message by getting its reference... but for that you would need app running. You can do this in different ways
1.Your app receive a localNotification
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification)
{
notification.alertBody = "new message"
}
You app launched via local notification
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
if let options = launchOptions {
// Do your checking on options here
let notif:UILocalNotification = options[UIApplicationLaunchOptionsLocalNotificationKey] as! UILocalNotification!
notif.alertBody = "new alert boxy"
}
return true
}
But in both cases there are chances you missed them as both case not guaranteed every time, so add different notifications for every day.

Resources