Local notifications not working (swift) - ios

I am looking to fire local notifications. I have tried to create this and I was successful, there were no errors but when I run the app in the simulator local notifications don't execute
code in app delegate
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert | .Badge | .Sound, categories: nil))
// play default sound
return true
}
and the view controller
class TechByteSchedulingViewController:UIViewController {
#IBOutlet weak var datePicker: UIDatePicker!
#IBAction func DateChosen(sender: UIButton) {
func sendNotification(sender: UIButton) {
var localNotification = UILocalNotification()
localNotification.fireDate = datePicker.date
localNotification.repeatInterval = .CalendarUnitDay
localNotification.alertBody = "check out your daily byte"
localNotification.alertAction = "Open"
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
localNotification.soundName = UILocalNotificationDefaultSoundName
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
application.applicationIconBadgeNumber = 0
}
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
override func viewDidDisappear(animated: Bool) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

Base on what I see you implement some function inside of the ButtonAction function which is wrong... you should implement the sendNotficationfunction outside of ButtonAction then called it inside of ButtonAction
class TechByteSchedulingViewController:UIViewController {
#IBOutlet weak var datePicker: UIDatePicker!
#IBAction func DateChosen(sender: UIButton) {
self.sendNotification()
}
func sendNotification() {
var localNotification = UILocalNotification()
localNotification.fireDate = datePicker.date
localNotification.repeatInterval = .CalendarUnitDay
localNotification.alertBody = "check out your daily byte"
localNotification.alertAction = "Open"
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
localNotification.soundName = UILocalNotificationDefaultSoundName
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
application.applicationIconBadgeNumber = 0
self.navigationController?.popToRootViewControllerAnimated(true)
}
}

Related

Call a function using NSTimer

So as the code shown below, the function loadView 3 is supposed to run 300 seconds(5 minutes) after the user tapped the button. But when I build and run, it does not. I also did a few experiments, I changed the timer to 5 seconds, it worked. So after the app is suspended from iOS system, the NSTimer doesn't run anymore? So what's the problem, how can I fix it?
#IBAction func buttonTapped(sender: AnyObject) {
NSTimer.scheduledTimerWithTimeInterval(300, target: self, selector: #selector(ViewController.loadView3), userInfo: nil, repeats: false)
createLocalNotification()
}
func createLocalNotification() {
let localnotification = UILocalNotification()
localnotification.fireDate = NSDate(timeIntervalSinceNow: 300)
localnotification.applicationIconBadgeNumber = 1
localnotification.soundName = UILocalNotificationDefaultSoundName
localnotification.alertBody = "Hello!"
UIApplication.sharedApplication().scheduleLocalNotification(localnotification)
}
func loadView3() {
label.text = "e89saa"
}
You could try something like this. The approach is, if timer works proceed with same logic, otherwise (probably app is killed or went to background), save firedDate and update UI before showing controller in method viewWillAppear.
#IBAction func buttonTapped(sender: AnyObject) {
NSTimer.scheduledTimerWithTimeInterval(300, target: self, selector: #selector(ViewController.loadView3), userInfo: nil, repeats: false)
createLocalNotification()
}
func createLocalNotification() {
let localnotification = UILocalNotification()
localnotification.fireDate = NSDate(timeIntervalSinceNow: 300)
localnotification.applicationIconBadgeNumber = 1
localnotification.soundName = UILocalNotificationDefaultSoundName
localnotification.alertBody = "Hello!"
UIApplication.sharedApplication().scheduleLocalNotification(localnotification)
// save in UserDefaults fireDate
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(localnotification.fireDate, forKey: "firedDate")
defaults.synchronize()
}
func loadView3() {
// reset in UserDefaults fireDate
let defaults = NSUserDefaults.standardUserDefaults()
defaults.removeObjectForKey("firedDate")
defaults.synchronize()
label.text = "e89saa"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated) // No need for semicolon
// retrieve fireDate from UserDefaults
let defaults = NSUserDefaults.standardUserDefaults()
let fireDate = defaults.objectForKey("firedData")
// check if we should update UI
if let _ = fireDate as? NSDate! {
if currentDate.compare(firedDate) == NSComparisonResult.OrderedDescending {
loadView3()
}
}
}

scheduleLocalNotification is not working in Swift 2.0

I'm a newbie in iOS technology.I'm trying to build an alarm app with swift 2.0 by using UILocalNotification. When I click button, I get the time and date from the UIPickerView. I want to display notification and play sound also.
But both sound and notification are not working. Please help me!
#IBOutlet weak var myPickerView: UIDatePicker!
override func viewDidLoad() {
super.viewDidLoad()
myPickerView.date = NSDate()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func setAlarmClicked(sender: UIButton) {
let dateFormater : NSDateFormatter = NSDateFormatter()
dateFormater.timeZone = NSTimeZone.defaultTimeZone()
dateFormater.timeStyle = .ShortStyle
dateFormater.dateStyle = .ShortStyle
let dateTimeString : NSString = dateFormater.stringFromDate(myPickerView.date)
print("date is \(dateTimeString)")
self.sheduleLocalNotificationWithDate(myPickerView.date)
}
#IBAction func cancelAlarmClicked(sender: UIButton) {
}
func sheduleLocalNotificationWithDate(fireDate : NSDate){
let localNotification : UILocalNotification = UILocalNotification()
localNotification.fireDate = fireDate
localNotification.alertBody = "Alert !!!!"
localNotification.soundName = "minion.mp3"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
You have to register for local notifications. Add this to your view controller:
override func viewDidAppear() {
super.viewDidAppear()
let settings = UIUserNotificationSettings(forTypes: [.Badge, .Sound, .Alert], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
}
An alert will come up when your view appears for the first time, hit "OK" and your notifications should work. Remember that the user can always disable notifications.

iOS notification not appearing on lockscren

For some reason my iOS app does not display my notification on the lockscreen
The notifications work perfectly when I use timeIntervalSinceNow...
but when I set up a time for the firedate I don't get it in the lockscreen
for some reason it gets displayed in the notification center, so the notification does get fired, just that it won't get displayed in the lockscreen.
I also get this message in the console whenever the notification is fired
from my research I know that this message is some kind of bug that happens on IOS 9, but does this have anything to do with my problem?
Here is the faulty code
class ViewController: UIViewController {
#IBOutlet weak var lol1: UIButton!
#IBOutlet weak var lol2: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func permission(sender: AnyObject) {
let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
}
#IBAction func notificatiolol(sender: AnyObject) {
let date:NSDateComponents = NSDateComponents()
date.year = 2016
date.month = 01
date.day = 12
date.hour = 5
date.minute = 57
let realDate = NSCalendar.currentCalendar().dateFromComponents(date)
let notification = UILocalNotification()
notification.fireDate = realDate
notification.alertBody = "Hey you! Yeah you! Swipe to unlock!"
notification.alertAction = "be awesome!"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = ["CustomField1": "w00t"]
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
}
and here is the code that works
class ViewController: UIViewController {
#IBOutlet weak var lol1: UIButton!
#IBOutlet weak var lol2: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func permission(sender: AnyObject) {
let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
}
#IBAction func notificatiolol(sender: AnyObject) {
let notification = UILocalNotification()
notification.fireDate = NSDate(timeIntervalSinceNow: 5)
notification.alertBody = "Hey you! Yeah you! Swipe to unlock!"
notification.alertAction = "be awesome!"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = ["CustomField1": "w00t"]
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
}
Thank you in advance, and sorry if this question is a duplicate

Cancel a local notification and schedule a new one

I have a problem. I have local notifications in my project, here is the code (thanks #leoDabus):
import UIKit
class ViewController: UIViewController {
#IBOutlet var datePicker: UIDatePicker!
#IBOutlet var notificationSwitch: UISwitch!
let localNotification = UILocalNotification()
override func viewDidLoad() {
super.viewDidLoad()
setUpNotificationsOptions()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidAppear(animated: Bool) {
guard let loadedDate = NSUserDefaults().dateForKey("datePicker") else { return }
datePicker.setDate(loadedDate, animated: false)
}
func setUpNotificationsOptions() {
datePicker.datePickerMode = .Time
localNotification.timeZone = NSTimeZone.localTimeZone()
localNotification.repeatInterval = .Day
localNotification.alertAction = "Open App"
localNotification.alertBody = news[0].titleNews
localNotification.soundName = UILocalNotificationDefaultSoundName
}
func toggleNotification() {
if notificationSwitch.on {
localNotification.fireDate = datePicker.date.fireDate
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
} else {
localNotification.fireDate = nil
UIApplication.sharedApplication().cancelLocalNotification(localNotification)
}
}
#IBAction func toggleSwitch(sender: UISwitch) {
toggleNotification()
}
#IBAction func dateChanged(sender: UIDatePicker) {
NSUserDefaults().setDate(sender.date, forKey: "datePicker")
toggleNotification()
} }
extension NSUserDefaults {
func setDate(date: NSDate, forKey:String) {
NSUserDefaults().setObject(date, forKey: forKey)
}
func dateForKey(string:String) -> NSDate? {
return NSUserDefaults().objectForKey(string) as? NSDate
}}
the problem is that my local notification alert Body news[0].titleNews is the result of a parser and it's a value that changes periodically. But with the code above i obtain every day the same string, not the updated one. There is a method to have everyday the updated news? Can I cancel last scheduled notification programmatically and scheduling new one?
Set a unique id in the userInfo property of UILocalNotification and when you get the updated status/news, traverse throught all the scheduled notifications , get your notification with that id you set earlier and now do your work accordingly.
Set your id like the following
localNotification.userInfo = ["notificationID" : "Your Id"]
Code for traversing scheduled notifications
let notificationArr:NSArray? = UIApplication.sharedApplication().scheduledLocalNotifications
notificationArr!.enumerateObjectsUsingBlock({ object, index, stop in
let notification = object as! UILocalNotification;
let userInfo = notification.userInfo! as NSDictionary
let notificationID = userInfo["notificationID"] as! String
if(notificationID == "Your set Id"){
UIApplication.sharedApplication().cancelLocalNotification(notification);
}
})

Set local notification for everyday at midnight

I'm trying to create a simple notification that will appear every day at midnight. This is the code I use:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil))
var thisDate = NSDateComponents()
thisDate.hour = 0
thisDate.minute = 0
thisDate.second = 0
var calender = NSCalendar()
var localNotification:UILocalNotification = UILocalNotification()
localNotification.timeZone = NSTimeZone.localTimeZone()
localNotification.fireDate = calender.dateFromComponents(thisDate)
localNotification.repeatInterval = .CalendarUnitDay
localNotification.alertAction = "Open App"
localNotification.alertBody = "Here is the seven o'clock notification"
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
return true
}
I cant figure out why it's not working, any idea?
There are many problems at your code so I will explain it with comments through the code as follow:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var midnightSwitch: UISwitch!
// you should declare your vars here
let localNotificationDailyAt12am = UILocalNotification()
// you should declare your funcions here
// you have to register the user notifications settings options (badge, alert and sound if desired)
func setUIUserNotificationOptions() {
UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Badge | UIUserNotificationType.Sound | UIUserNotificationType.Alert, categories: nil))
}
// now lets setup your notification
func notificationsOptions12am() {
// defines localtime
localNotificationDailyAt12am.timeZone = NSTimeZone.localTimeZone()
// confirms the alert dialog box action
localNotificationDailyAt12am.hasAction = true
// defines the notification alert body text
localNotificationDailyAt12am.alertBody = "The midnight notification message"
// defines the daily time interval
localNotificationDailyAt12am.repeatCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
localNotificationDailyAt12am.repeatInterval = .CalendarUnitDay
// defines the notification alert button text
localNotificationDailyAt12am.alertAction = "Open App"
// defines the default sound for your notification
localNotificationDailyAt12am.soundName = UILocalNotificationDefaultSoundName
// increments the badge counter
localNotificationDailyAt12am.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
// defines your firedate tomorrow at 12am ( note: extension NSDate tomorrowAt12am at the bottom )
localNotificationDailyAt12am.fireDate = NSDate().tomorrowAt12am
// lets set it up
UIApplication.sharedApplication().scheduleLocalNotification(localNotificationDailyAt12am)
}
override func viewDidLoad() {
super.viewDidLoad()
setUIUserNotificationOptions()
notificationsOptions12am()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func switched(sender: AnyObject) {
localNotificationDailyAt12am.fireDate = midnightSwitch.on ?
NSDate().tomorrowAt12am : // tomorrow at 12am
NSDate().dateByAddingTimeInterval(3155673600) // will never fire (100 years from now)
}
}
extension NSDate {
var day: Int { return NSCalendar.currentCalendar().components(.Day, fromDate: self).day }
var month: Int { return NSCalendar.currentCalendar().components(.Month, fromDate: self).month }
var year: Int { return NSCalendar.currentCalendar().components(.Year, fromDate: self).year }
var tomorrowAt12am: NSDate {
return NSCalendar.currentCalendar().dateWithEra(1, year: year, month: month, day: day+1, hour: 0, minute: 0, second: 0, nanosecond: 0)!
}
}
Try also set day, month and year for date components:
var thisDate = NSDateComponents()
thisDate.hour = 0
thisDate.minute = 0
thisDate.second = 0

Resources