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);
Related
I am new to iOS and Swift. I am implementing remote notification in my app. Everything works fine when the app is active or in the background. But my notification does not show up when the app is terminated. All I am getting is the alert sound of the notification.
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
if #available(iOS 10.0, *){
}else{
let notification = UILocalNotification()
notification.alertTitle = "my Title"
notification.alertBody = "My Message"
notification.category = "customCategory"
notification.soundName = UILocalNotificationDefaultSoundName
application.scheduleLocalNotification(notification)
}
}
Below AppDelegate method will be called When you receive a notification and application is in killed state
didFinishLaunchingWithOptions
So you should handle it properly from here when app is in killed state.
Below code helps to identify the Remote/push or Local notification in didFinishLaunchingWithOptions method:
if let launchOpts = launchOptions as [UIApplicationLaunchOptionsKey: Any]? {
if let notificationPayload = launchOpts[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary {
//Handle push notification here
}
else if let notification = (launchOpts as NSDictionary).object(forKey: "UIApplicationLaunchOptionsLocalNotificationKey") as? UILocalNotification {
//Handle local notification here
}
I am creating local notification when app receiving Push notification. these local notification generating when app in foreground and when i am creating local notification at the same time didReceiveLocalNotification method is calling and getting difficulties to manage local notification and clicking/tap on location same event calling twice.I need to avoids duplicate Local notifications also.
Please help me for solve this issue.
//MARK: - Delegate Method For APNS Notification
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
print("Notification Message \(userInfo)")
let aps = userInfo["aps"] as! [String: AnyObject]
// 1
if userInfo["postData"] != nil {
// Refresh Promotions
print("Got it...")
// Clear Previous Value Data
postData.removeAll()
//Adding New Post Data here
if (userInfo["postData"] != nil){
self.postData = userInfo["postData"]! as! [String : AnyObject]
print(self.postData)
}
//Condition here for Notification
if appInForeground == false {
//Goto Promo List
//Set Boolean for View
notiDetails = true
//Navigation
gotoPromoListView()
}else{
let systemSoundID: SystemSoundID = 1016
// to play sound
AudioServicesPlaySystemSound (systemSoundID)
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
let notification = UILocalNotification()
notification.alertBody = (aps["alert"] as? String)!
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = userInfo["postData"]! as! [String : AnyObject]
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
How to manage this method for local notification
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
// Do something serious in a real app.
print("Received Local Notification:")
print(notification.userInfo)
self.postData = notification.userInfo as! [String : AnyObject]
didTapNotification()
}
Could you please show your code, where you register your remote notifications?
If you want to show alert and badge, when receive push notifications, you can make like this:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let notificationTypes: UIUserNotificationType = [.Alert, .Badge, .Sound]
let notificationSettings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
return true
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
UIApplication.sharedApplication().registerForRemoteNotifications()
}
After that you can add custom actions to method:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject :
}
If you need local notifications, you should set fire property, when you schedule notification:
let localNotification = UILocalNotification()
localNotification.fireDate = NSDate()
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.alertBody = text
localNotification.soundName = UILocalNotificationDefaultSoundName
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
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