How to Set Up Push Notifications in Swift

How to set up push notifications in Swift

While the answer is given well to handle push notification, still I believe to share integrated complete case at once to ease:

To 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

// If granted comes true you can enabled features based on authorization.
guard granted else { return }

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
{
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 allowed notifications")

case .notSupported:
print("something went wrong here")
}
}

So the checklist of APNS:

  • Create AppId allowed with Push Notification
  • Create SSL certificate with valid certificate and app id
  • Create Provisioning profile with same certificate and make sure to add device in case of sandboxing(development provisioning)

Note: That will be good if Create Provisioning profile after SSL Certificate.

With Code:

  • Register app for push notification
  • Handle didRegisterForRemoteNotificationsWithDeviceToken method
  • Set targets> Capability> background modes> Remote Notification
  • Handle didReceiveRemoteNotification

How to enable push notification from app settings in iOS Swift 5?

Once a user has denied the permissions for push notifications, he has to enable them from within the settings app in order to get push notifications. So on your settings screen, when user taps on enable notification option just take him to the notifications settings screen of your app. And from there he can enable it. Use this piece of code for opening settings app.

if let bundle = Bundle.main.bundleIdentifier,
let settings = URL(string: UIApplication.openSettingsURLString + bundle) {
if UIApplication.shared.canOpenURL(settings) {
UIApplication.shared.open(settings)
}
}

After enabling from within the settings app, status won't be denied anymore.

How to enable push notifications in Xcode 12

Not all capabilities are available depending on if you are using a paid Developer Program account, or working with Xcode's free provisioning.

Pertaining to Capabilities/what you can or can't do based on account type - the link is: https://developer.apple.com/support/app-capabilities/

how to setting up AppDelegate for push notification in swift

  1. Yes, you can manage the content of notification by sending an appropriate payload in the notification. Sending the payload in the following pattern would show title and body in the notification
{
"aps" : {
"alert" : {
"title" : "Game Request",
"body" : "Bob wants to play poker",
},
"badge" : 5
}
}

  1. Display the notification is handled by the system depending upon the app state. If the app is the foreground state you will get the call in the didReceiveRemoteNotification, otherwise, the system handles the displaying part and get control in the app when the user taps on the notification.

You cannot edit the content of notification from the app side.


  1. According to the document

APNs can issue a new device token for a variety of reasons:

User installs your app on a new device

User restores device from a backup

User reinstalls the operating system

Other system-defined events

So its recommended requesting device token at launch time.

You can send the token in login page rather than requesting a new token in the login.

How to jump from system push notifications settings to personal push notifications settings in the application?

On the request notification authorization you should add providesAppNotificationSettings like below.

UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound, .providesAppNotificationSettings])

After that you need to redirect user to your app's settings page below function.

func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) { // Redirect User to App Settings Page}


Related Topics



Leave a reply



Submit