Skip to content

Instantly share code, notes, and snippets.

@aksyuma
Created July 23, 2020 07:17
Show Gist options
  • Select an option

  • Save aksyuma/43e8afd108a395764f464ea8bd6473f0 to your computer and use it in GitHub Desktop.

Select an option

Save aksyuma/43e8afd108a395764f464ea8bd6473f0 to your computer and use it in GitHub Desktop.
//
// AppDelegate.swift
//
// Created by Syuma, Amos on 2020/06/12.
// Copyright © 2020 Syuma, Amos. All rights reserved.
//
import UIKit
import AWSPinpoint
import AWSMobileClient
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
var pinpoint: AWSPinpoint?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Calling this method here ensures the app will attempt to register for push notifications any time it’s launched.
registerForPushNotifications()
// Verbose Logging for AWS iOS SDK
//AWSDDLog.sharedInstance.logLevel = .verbose
//AWSDDLog.add(AWSDDTTYLogger.sharedInstance)
// Create AWSMobileClient to connect with AWS
let didFinishLaunching = AWSMobileClient.sharedInstance().interceptApplication(application, didFinishLaunchingWithOptions: launchOptions)
// AWS Pinpoint initialization
pinpoint = AWSPinpoint(configuration:AWSPinpointConfiguration.defaultPinpointConfiguration(launchOptions: launchOptions))
UIApplication.shared.registerForRemoteNotifications()
return didFinishLaunching
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
// Clear the badge icon when you open the app.
UIApplication.shared.applicationIconBadgeNumber = 0
}
// Called when APNs has assigned the device a unique token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
print("Device Token: \(token)")
// Register the device token with Pinpoint as the endpoint for this user
pinpoint!.notificationManager.interceptDidRegisterForRemoteNotifications(withDeviceToken: deviceToken)
}
// Called when APNs failed to register the device for push notifications
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
// Print the error to console (you should alert the user that registration failed)
print("APNs registration failed: \(error)")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
pinpoint!.notificationManager.interceptDidReceiveRemoteNotification(userInfo, fetchCompletionHandler: completionHandler)
// This is where you intercept push notifications.
if (application.applicationState == .active) {
let alert = UIAlertController(title: "Notification Received",
message: userInfo.description,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion:nil)
}
}
// Request user to grant permissions for the app to use notifications
func registerForPushNotifications() {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options:
[.alert, .badge, .sound]){(granted, error) in
print("Permission Granted: \(granted)")
// 1. Check if permission granted
guard granted else { return }
// 2. Attempt registration for remote notifications on the main thread
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment