I am trying to display a local notification when my app is in the foreground. I have no problems displaying a remote notification but I am having issues when the app is running in the foreground. I am only having issues with the new iOS 10.
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// TODO: Handle data of notification
if application.applicationState == UIApplicationState.Active {
//print("Message ID: \(userInfo["gcm.message_id"]!)")
//print("Message ID: \(userInfo.keys)")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if (userInfo["notice"] != nil) {
if #available(iOS 10.0, *) {
print ("yes")
let content = UNMutableNotificationContent()
content.title = "My Car Wash"
content.body = (userInfo["notice"] as? String)!
}
else
{
let localNotification = UILocalNotification()
localNotification.fireDate = NSDate(timeIntervalSinceNow:0)
localNotification.alertBody = userInfo["notice"] as? String
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.alertAction = nil
localNotification.timeZone = NSTimeZone.defaultTimeZone()
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
let systemSoundID: SystemSoundID = 1000
// to play sound
AudioServicesPlaySystemSound (systemSoundID)
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
completionHandler(.NewData)
}
}
})}
}
My iPhone is running iOS 10 and I can see "yes" is printed out. My app has the required notification permissions .
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Register for remote notifications
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
// [END register_for_notifications]
FIRApp.configure()
// Add observer for InstanceID token refresh callback.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification),
name: kFIRInstanceIDTokenRefreshNotification, object: nil)
return true
}
As mentioned on iOS 9 devices the code works and I get notifications when the app is not running. The issue is with iOS 10 when the app is in the foreground. I have been searching google for a while but I am still not there. Any help or suggestions would be greatly appreciated.