Here is how I configured the AppDelegate file for this:
To handle push notifications, import the following structure:
import UserNotifications
To make the phone vibrate on any device, import the following structure:
import AudioToolbox
Make your AppDelegate 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 previously said that your application can send notifications. If not, process it as you like.
To access the device token after registration:
hexString is an extension added to my project:
extension Data { var hexString: String { return map { String(format: "%02.2hhx", arguments: [$0]) }.joined() } }
To deal with what happens when your application 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 deal with what happens when your application receives a notification in the background, after which the user clicks on the notification:
//Called when a notification is delivered to 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() }