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
}
Related
I have added these in didFinishLaunchingWithOptions
let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
self.createLocalNotification()
And then, calling below function.
func createLocalNotification() {
let localNotification = UILocalNotification()
localNotification.fireDate = NSDate(timeIntervalSinceNow: 3)
// localNotification.applicationIconBadgeNumber = 1
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.userInfo = [
"id": "not_id0",
"message": "Check notification"
]
localNotification.alertBody = "Check notification"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
To cancel this notification, I have tried below in didReceiveLocalNotification But still display notification every App launching.
let app:UIApplication = UIApplication.sharedApplication()
for oneEvent in app.scheduledLocalNotifications! {
let notification = oneEvent as UILocalNotification
let userInfoCurrent = notification.userInfo! as! [String:AnyObject]
let id = userInfoCurrent["id"]! as! String
if id == "not_id0" {
//Cancelling local notification
app.cancelLocalNotification(notification)
break;
}
}
How Can I create first time local notification? If someone explain It would be great.
You could use NSUserDefaults as such:
In didFinishLaunchingWithOptions: in your AppDelegate:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
...
if let haveShownFirstRunNotification = NSUserDefaults.standardUserDefaults().boolForKey("haveShownFirstRunNotification") {
if !haveShownFirstRunNotification {
createLocalNotification()
}
}
...
}
And in createLocalNotification:
func createLocalNotification() {
...
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "haveShownFirstRunNotification")
}
Add flag in in userDefaults and then check if
NSUserDefaults.standardUserDefaults().boolForKey("notified")
if not, open notification method and there place
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "notified")
I'm trying to send a UILocalNotification like this:
func sendNotifiaction() {
let notification = UILocalNotification()
notification.userInfo = [
"Identifier": self.identifier!
]
notification.alertTitle = "Alarm!"
notification.alertBody = "test"
//notification.soundName = "Temporary-bleep-sound.aiff"
notification.category = "category"
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
I tried to put a break point on this method and it is being called and run, but the notification doesn't sent at all.
Anyone has an idea why?
You gotta to register the Notification first
UIApplication.sharedApplication().cancelAllLocalNotifications()
let settings = UIUserNotificationSettings(forTypes: .Alert, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
Here's my demo for Notification firing at a specific time
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
UIApplication.sharedApplication().cancelAllLocalNotifications()
let settings = UIUserNotificationSettings(forTypes: .Alert, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
let localNotification1 = UILocalNotification()
localNotification1.alertBody = "Your alert message at 9:00 pm"
localNotification1.timeZone = NSTimeZone.defaultTimeZone()
localNotification1.fireDate = self.getNinePMDate()
UIApplication.sharedApplication().scheduleLocalNotification(localNotification1)
return true
}
func getNinePMDate() -> NSDate? {
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let now: NSDate! = NSDate()
let date21h = calendar.dateBySettingHour(21, minute: 0, second: 0, ofDate: now, options: NSCalendarOptions.MatchFirst)
return date21h
}
}
You should implement didReceiveLocalNotification in appdelegate and you have to show alert view manually with title and message as alertbody of your notification.
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.
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]
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