Push notification is most important part of the app so while we are adding push notification in our iOS app we need to complete following setup.

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

IOS 9

var settings : UIUserNotificationSettings = UIUserNotificationSettings(forTypes:UIUserNotificationType.Alert|UIUserNotificationType.Sound, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()

After IOS 10

Introduced UserNotifications framework:

Import the UserNotifications framework and add the UNUserNotificationCenterDelegate in AppDelegate.swift

To Register Application for APNS

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: NSData) {
//send this device token to server
}//Called if unable to register for APNS.
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {println(error)}

On Receiving notification following delegate will call:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {    println("Recived: \(userInfo)")
//Parsing userinfo:
var temp : NSDictionary = userInfo
if let info = userInfo["aps"] as? Dictionary<String, AnyObject>
{
var alertMsg = info["alert"] as! String
var alert: UIAlertView!
alert = UIAlertView(title: "", message: alertMsg, delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
}

To be identify the permission given we can use:

UNUserNotificationCenter.current().getNotificationSettings(){ (setttings) in        switch setttings.soundSetting{
case .enabled:
print("enabled sound") case .disabled:
print("not…
Mr.Javed Multani

Software Engineer | Certified ScrumMaster® (CSM) | UX Researcher | Youtuber | Tech Writer