How to set up push notifications in Swift

后端 未结 11 1190
生来不讨喜
生来不讨喜 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:52

    Swift 4

    Import the UserNotifications framework and add the UNUserNotificationCenterDelegate in AppDelegate

    import UserNotifications
    
    class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate
    

    To Register Application for APNS, (Include the following code in didFinishLaunchingWithOptions method inside AppDelegate.swift)

    let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
            // Enable or disable features based on authorization.
        }
        application.registerForRemoteNotifications()
    

    This will call following delegate method

    func application(_ application: UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        //send this device token to server
    
    }
    
    //Called if unable to register for APNS.
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print(error)
    }
    

    On Receiving notification following delegate will call:

    private func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    
        print("Recived: \(userInfo)")
        //Parsing userinfo:
    
    }
    

提交回复
热议问题