How to set up push notifications in Swift

后端 未结 11 1202
生来不讨喜
生来不讨喜 2020-11-27 10:48

I am trying to set up a push notification system for my application. I have a server and a developer license to set up the push notification service.

I am currently

11条回答
  •  天涯浪人
    2020-11-27 11:42

    Swift 4

    I think this is the correct way for setup in iOS 8 and above.

    Turn on Push Notifications in the Capabilities tab

    Import UserNotifications

    import UserNotifications
    

    Modify didFinishLaunchingWithOptions

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
    
        if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject] {
    
            // If your app wasn’t running and the user launches it by tapping the push notification, the push notification is passed to your app in the launchOptions
    
            let aps = notification["aps"] as! [String: AnyObject]
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
    
        registerForPushNotifications()
    
        return true
    }
    

    It’s extremely important to call registerUserNotificationSettings(_:) every time the app launches. This is because the user can, at any time, go into the Settings app and change the notification permissions. application(_:didRegisterUserNotificationSettings:) will always provide you with what permissions the user currently has allowed for your app.

    Copy paste this AppDelegate extension

    // Push Notificaion
    extension AppDelegate {
    func registerForPushNotifications() {
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
                [weak self] (granted, error) in
                print("Permission granted: \(granted)")
    
                guard granted else {
                    print("Please enable \"Notifications\" from App Settings.")
                    self?.showPermissionAlert()
                    return
                }
    
                self?.getNotificationSettings()
            }
        } else {
            let settings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(settings)
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
    
    @available(iOS 10.0, *)
    func getNotificationSettings() {
    
        UNUserNotificationCenter.current().getNotificationSettings { (settings) in
            print("Notification settings: \(settings)")
            guard settings.authorizationStatus == .authorized else { return }
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    
        let tokenParts = deviceToken.map { data -> String in
            return String(format: "%02.2hhx", data)
        }
    
        let token = tokenParts.joined()
        print("Device Token: \(token)")
        //UserDefaults.standard.set(token, forKey: DEVICE_TOKEN)
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register: \(error)")
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    
        // If your app was running and in the foreground
        // Or
        // If your app was running or suspended in the background and the user brings it to the foreground by tapping the push notification
    
        print("didReceiveRemoteNotification /(userInfo)")
    
        guard let dict = userInfo["aps"]  as? [String: Any], let msg = dict ["alert"] as? String else {
            print("Notification Parsing Error")
            return
        }
    }
    
    func showPermissionAlert() {
        let alert = UIAlertController(title: "WARNING", message: "Please enable access to Notifications in the Settings app.", preferredStyle: .alert)
    
        let settingsAction = UIAlertAction(title: "Settings", style: .default) {[weak self] (alertAction) in
            self?.gotoAppSettings()
        }
    
        let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    
        alert.addAction(settingsAction)
        alert.addAction(cancelAction)
    
        DispatchQueue.main.async {
            self.window?.rootViewController?.present(alert, animated: true, completion: nil)
        }
    }
    
    private func gotoAppSettings() {
    
        guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
            return
        }
    
        if UIApplication.shared.canOpenURL(settingsUrl) {
            UIApplication.shared.openURL(settingsUrl)
        }
    }
    }
    

    Check out: Push Notifications Tutorial: Getting Started

提交回复
热议问题