Swift - How creating first time app launch local notification? - ios

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")

Related

Not able to play the music when recived LocalNotification, when app is in background state in swift

I'm scheduling up a Local Notification as an alarm for an app, where I'm setting music and vibration when local notification is received. When app is in foreground state everything is working fine, music is playing, vibration is there.
But when app is in background state only the default notification music i.e once only not in repeat and single vibration is occurring.
func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
//show an alert window
var isSnooze: Bool = false
var soundName: String = ""
var index: Int = -1
if let userInfo = notification.userInfo {
isSnooze = userInfo["snooze"] as! Bool
soundName = userInfo["soundName"] as! String
index = userInfo["index"] as! Int
}
playSound(soundName)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let mainVC = storyboard.instantiateViewController(withIdentifier: "HomeViewController") as? HomeViewController
mainVC?.notification = notification
mainVC?.isFromNotificationDelegate = true
let nav = UINavigationController(rootViewController: mainVC!)
self.window?.rootViewController = nav
}
Register for notifications in AppDellegate.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Sound | .Alert | .Badge, categories: nil))
return true
}
Now, schedule your notification using following func, it will automatically play your custom sound whenever notification receieves
func localnotification (firedate:NSDate) {
var localNotification:UILocalNotification = UILocalNotification()
localNotification.fireDate = firedate
localNotification.alertBody = "time to woke up"
localNotification.soundName = "alarm.wav"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}

How to manage Local Notification in swift

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)

UILocalNotification doesn't send

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.

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

Interactive Notification not showing buttons ios 9.2

I believe I am creating interactive notifications properly, but I get notifications on springboard/lock screen w/out buttons. What am I doing wrong?
AppDelegate:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let notificationSettings: UIUserNotificationSettings! = UIApplication.sharedApplication().currentUserNotificationSettings()
/// don't want to constantly set/re-set when this function fires
if (notificationSettings.types == UIUserNotificationType.None){
let yesAction = UIMutableUserNotificationAction()
yesAction.identifier = "yesAction"
yesAction.title = "Yes"
yesAction.destructive = false
yesAction.authenticationRequired = false
yesAction.activationMode = UIUserNotificationActivationMode.Background
let noAction = UIMutableUserNotificationAction()
noAction.identifier = "noAction"
noAction.title = "No"
noAction.destructive = false
noAction.authenticationRequired = false
noAction.activationMode = UIUserNotificationActivationMode.Background
let stopAction = UIMutableUserNotificationAction()
stopAction.identifier = "stopAction"
stopAction.title = "Stop"
stopAction.destructive = true
stopAction.authenticationRequired = false
stopAction.activationMode = UIUserNotificationActivationMode.Background
let encouragementCategory = UIMutableUserNotificationCategory()
encouragementCategory.identifier = "GOCEncouragement"
encouragementCategory.setActions([yesAction, noAction, stopAction], forContext: UIUserNotificationActionContext.Default)
encouragementCategory.setActions([yesAction, noAction], forContext: UIUserNotificationActionContext.Minimal)
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: Set.init(arrayLiteral: encouragementCategory))
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
}
return true
}
Somewhere else, called by application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings):
notificationArray.forEach({
let notification = UILocalNotification.init()
notification.fireDate = fireDay
notification.soundName = UILocalNotificationDefaultSoundName
notification.alertBody = $0["Encouragement"] as! String!
notification.repeatInterval = .Month
notification.category = "GOCEncouragement"
notification.userInfo = [ "UUID" : $0["UUID"] as! Int]
if #available(iOS 8.2, *) {
notification.alertTitle = "Choices Encouragement"
}
UIApplication.sharedApplication().scheduleLocalNotification(notification)
nextDay.day++
fireDay = NSCalendar.currentCalendar().dateByAddingComponents(nextDay, toDate: fireDay!, options: NSCalendarOptions.init(rawValue: 0))
})
To re-iterate the problem; notifications appear on schedule, but left-slide on lock screen doesn't reveal any buttons, nor does tugging down on home screen.
Any suggestions welcome!
Edit: thought it was simulator-only, but is on live 9.2 devices as well. Other iOS versions work as expected.

Resources