2

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.

Paul_D
  • 255
  • 2
  • 8
  • 21
  • this should help you: https://makeapppie.com/2016/08/08/how-to-make-local-notifications-in-ios-10/#comments – Do2 Sep 22 '16 at 02:35
  • With Objective-C method http://stackoverflow.com/questions/37938771/uilocalnotification-is-deprecated-in-ios10/37969401#37969401 – ChenYilong Oct 26 '16 at 03:32

1 Answers1

3

Your code doesn't work in iOS10, you must use

UserNotifications framework

For devices running iOS 9 and below, implement AppDelegate application:didReceiveRemoteNotification: to handle notifications received when the client app is in the foreground

For devices running iOS 10 and above, implement

UNUserNotificationCenterDelegate userNotificationCenter:willPresentNotification:withCompletionHandler:

to handle notifications received when the client app is in the foreground (from here https://firebase.google.com/docs/notifications/ios/console-audience)

You code must be something like that (For Firebase notifications):

import UIKit
import UserNotifications

import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

  func application(application: UIApplication,
                   didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    // [START register_for_notifications]
    if #available(iOS 10.0, *) {
      let authOptions : UNAuthorizationOptions = [.Alert, .Badge, .Sound]
      UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
        authOptions,
        completionHandler: {_,_ in })

      // For iOS 10 display notification (sent via APNS)
      UNUserNotificationCenter.currentNotificationCenter().delegate = self
      // For iOS 10 data message (sent via FCM)
      FIRMessaging.messaging().remoteMessageDelegate = self

    } else {
      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
  }

  // [START receive_message]
  func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                   fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print("%@", userInfo)
  }
  // [END receive_message]

  // [START refresh_token]
  func tokenRefreshNotification(notification: NSNotification) {
    if let refreshedToken = FIRInstanceID.instanceID().token() {
      print("InstanceID token: \(refreshedToken)")
    }

    // Connect to FCM since connection may have failed when attempted before having a token.
    connectToFcm()
  }
  // [END refresh_token]

  // [START connect_to_fcm]
  func connectToFcm() {
    FIRMessaging.messaging().connectWithCompletion { (error) in
      if (error != nil) {
        print("Unable to connect with FCM. \(error)")
      } else {
        print("Connected to FCM.")
      }
    }
  }
  // [END connect_to_fcm]

  func applicationDidBecomeActive(application: UIApplication) {
    connectToFcm()
  }

  // [START disconnect_from_fcm]
  func applicationDidEnterBackground(application: UIApplication) {
    FIRMessaging.messaging().disconnect()
    print("Disconnected from FCM.")
  }
  // [END disconnect_from_fcm]
}

// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(center: UNUserNotificationCenter,
                              willPresentNotification notification: UNNotification,
    withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo
    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print("%@", userInfo)
  }
}

extension AppDelegate : FIRMessagingDelegate {
  // Receive data message on iOS 10 devices.
  func applicationReceivedRemoteMessage(remoteMessage: FIRMessagingRemoteMessage) {
    print("%@", remoteMessage.appData)
  }
}

// [END ios_10_message_handling]

from here: https://github.com/firebase/quickstart-ios/blob/master/messaging/FCMSwift/AppDelegate.swift

TonyMkenu
  • 7,597
  • 3
  • 27
  • 49