Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle ios push notifications when the app is in the foreground?

How do I set up my AppDelegate to handle push notifications that occur when the app is in the foreground and in the background with swift 3 and ios 10? Including how to make the phone vibrate while in the foreground if I receive a notifcation.

like image 968
havak5 Avatar asked Feb 09 '17 02:02

havak5


People also ask

How do I show notification when an app is in foreground iOS?

For displaying banner message while app is in foreground, use the following method. You must also register your app delegate as the delegate for the notifications center: import UserNotifications // snip! class AppDelegate : UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate // snip!

Do push notifications work when app is open?

You have to put in the notification message title, icon, and content. You can send these messages using the Firebase console UI. In this way, a notification will be shown when the app is running in the background. Data Message: The app should handle these messages.

Do push notifications work when app is closed iOS?

Apple does not offer a way to handle a notification that arrives when your app is closed (i.e. when the user has fully quit the application or the OS had decided to kill it while it is in the background). If this happens, the only way to handle the notification is to wait until it is opened by the user.

How do I keep notifications in front of my iPhone?

To display the contents of notifications on the Lock Screen without unlocking your device, go to Settings > Notifications > Show Previews and select Always.


1 Answers

Here is how I set up my AppDelegate file to do this:

To handle push notifications, import the following framework:

import UserNotifications

To make the phone vibrate on any device import the following framework:

import AudioToolbox

Make your AppDelegate a UNUserNotificationCenterDelegate:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

In your "didFinishLaunchingWithOptions" add this:

    UNUserNotificationCenter.current().delegate = self
    UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert], completionHandler: {(granted, error) in
        if (granted) {
            UIApplication.shared.registerForRemoteNotifications()
        } else{
            print("Notification permissions not granted")
        }
    })

This will determine if the user has previously said that your app can send notifications. If not, handle it how you please.

To get access to the device token once it is registered:

//Completed registering for notifications. Store the device token to be saved later
func application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) {

    self.deviceTokenString = deviceToken.hexString
}

hexString is an extension I added to my project:

extension Data {
    var hexString: String {
        return map { String(format: "%02.2hhx", arguments: [$0]) }.joined()
    }
}

To handle what happens when your app receives a notification in the foreground:

//Called when a notification is delivered to a foreground app.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    //Handle the notification
    //This will get the text sent in your notification
    let body = notification.request.content.body

    //This works for iphone 7 and above using haptic feedback
    let feedbackGenerator = UINotificationFeedbackGenerator()
    feedbackGenerator.notificationOccurred(.success)

    //This works for all devices. Choose one or the other. 
    AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate), nil)
}

To handle what happens when a users presses on a notification they receive (from your application) while your app is in the background, call the following function:

//Called when a notification is interacted with for a background app.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    //Handle the notification
    print("did receive")
    let body = response.notification.request.content.body
    completionHandler()

}
like image 83
havak5 Avatar answered Oct 17 '22 00:10

havak5