havak5
havak5

Reputation: 724

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.

Upvotes: 7

Views: 8348

Answers (2)

Crono
Crono

Reputation: 2054

I would add to havak5's answer that you can set push notifications to be shown as iOS default push, just like this:

swift code:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        if UIApplication.shared.applicationState == .active {
            completionHandler( [.alert,.sound]) // completionHandler will show alert and sound from foreground app, just like a push that is shown from background app
        }
    }

Upvotes: 2

havak5
havak5

Reputation: 724

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

}

Upvotes: 11

Related Questions