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
Related
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.
Can anyone help me how to use the state of a UISwitch to turn on/off local notifications declared in Appdelegate.swift ?
Viewcontroller.swift:
#IBOutlet weak var switchButton: UISwitch!
var switchState = true
let switchKey = "switchState"
#IBAction func saveSwitchPressed(sender: AnyObject) {
NSUserDefaults.standardUserDefaults().setBool(switchButton.on, forKey: "switchState")
}
override public func viewDidLoad() {
super.viewDidLoad()
switchButton.on = NSUserDefaults.standardUserDefaults().boolForKey("switchState")
}
AppDelegate.swift
func handleRegionEvent(region: CLRegion) {
// Show an alert if application is active
if UIApplication.sharedApplication().applicationState == .Active {
if let message = notefromRegionIdentifier(region.identifier) {
if let viewController = window?.rootViewController {
showSimpleAlertWithTitle(nil, message: message, viewController: viewController)
}
}
} else {
// Otherwise present a local notification
let notification = UILocalNotification()
notification.alertBody = notefromRegionIdentifier(region.identifier)
notification.soundName = "Default";
UIApplication.sharedApplication().presentLocalNotificationNow(notification)
}
}
This should can be accomplished using targetAction
override public func viewDidLoad() {
super.viewDidLoad()
switchButton.on = NSUserDefaults.standardUserDefaults().boolForKey("switchState")
//Set button to observe target action
switchButton.addTarget(self, action: "presentNotification", forControlEvents: UIControlEvents.ValueChanged)
}
func presentNotification() {
//Do notification stuff here
}
I was using the ViewController class before to get the users updates but now when expanding the application i needed to move it to another class that simply handles all the location updates. Here is the code that i am using now:
class ViewController: UIViewController, UITextFieldDelegate {
#IBAction func pickMeUpButton(sender: AnyObject) {
sendPushNotificationController().sendPushNotification("sendRequest",userLat: defaults.stringForKey("userLat")!, userLong: defaults.stringForKey("userLong")! )
}
#IBOutlet var numberForPickup: UITextField!
let defaults = NSUserDefaults.standardUserDefaults()
override func viewDidLoad() {
super.viewDidLoad()
self.numberForPickup.delegate = self
getLocationController().initLocation()
}
So i made another class called getLocationController with an init function that should start the location updates. Here is the code:
class getLocationController: UIViewController, CLLocationManagerDelegate {
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func initLocation(){
print("Im in here")
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
print("In location")
if UIApplication.sharedApplication().applicationState == .Active {
print("App in Foreground")
}else {
let Device = UIDevice.currentDevice()
let iosVersion = Double(Device.systemVersion) ?? 0
let iOS9 = iosVersion >= 9
if iOS9{
locationManager.allowsBackgroundLocationUpdates = true;
locationManager.pausesLocationUpdatesAutomatically = false;
}
//let iOS7 = iosVersion >= 7 && iosVersion < 8
print("App is backgrounded. New location is %#", newLocation)
}
}
}
Now the print in initLocation is printed but not the print in didUpdateLocations. I used the very same code in ViewController class and it worked perfectly fine. Now when i am trying to move it to another class that is now really a view on the phone but simply a helper class its not working. Any ideas why?
I don't see you assigning the getLocationController to a variable anywhere in the ViewController. That means the getLocationController would go out of scope and be destroyed, wouldn't it? That would explain why the callback didUpdateToLocation isn't called.
Try:
class ViewController: UITextFieldDelegate {
#IBAction func pickMeUpButton(sender: AnyObject) {
sendPushNotificationController().sendPushNotification("sendRequest",userLat: defaults.stringForKey("userLat")!, userLong: defaults.stringForKey("userLong")! )
}
#IBOutlet var numberForPickup: UITextField!
let defaults = NSUserDefaults.standardUserDefaults()
var glc:getLocationController // is this how it is in Swift?!
override func viewDidLoad() {
super.viewDidLoad()
self.numberForPickup.delegate = self
glc = getLocationController()
glc.initLocation()
}
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);
}
})
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)
}
}