Implement Push Notifications in iOS with Swift

Get an Apple Developer Account

Activate Push notifications in your iOS project

Registered App ID in Apple Developer Account
Registered App ID in Apple Developer Account

Request permission for User notifications

import UIKit
import UserNotifications

extension UIViewController {

func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
//print("User Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}

func requestNotificationAuthorization(){
// Request for permissions
UNUserNotificationCenter.current()
.requestAuthorization(
options: [.alert, .sound, .badge]) {
[weak self] granted, error in
//print("Notification granted: \(granted)")
guard granted else { return }
self?.getNotificationSettings()
}
}

}
import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
requestNotificationAuthorization()
}


}
import UIKit

extension AppDelegate {

func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
let tokenParts = deviceToken.map
{ data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
print("My Device Token: \(token)")
}

func application(
_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Error registering notifications: \(error)")
}
}
Error registering notifications: Error Domain=NSCocoaErrorDomain Code=3010 "remote notifications are not supported in the simulator" UserInfo={NSLocalizedDescription=remote notifications are not supported in the simulator}
Request Permission for User Notifications
Request Permission for User Notifications
Notification granted: true
User Notification settings: <UNNotificationSettings: 0x282834380; authorizationStatus: Authorized, notificationCenterSetting: Enabled, soundSetting: Enabled, badgeSetting: Enabled, lockScreenSetting: Enabled, carPlaySetting: NotSupported, criticalAlertSetting: NotSupported, alertSetting: Enabled, alertStyle: Banner, providesAppNotificationSettings: No>
My Device Token: 930976dfb191c5085b72aa347ad91c561a6fcdaab639c173a015f0745ee11401

Register in Apple Push Notifications service

Test Push Notifications

Handling Push Notifications in your app

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {        // Override point for customization after application launch.

// Check remote notification
let notificationOption = launchOptions?[.remoteNotification]
if let notification = notificationOption as? [String: AnyObject],
let aps = notification["aps"] as? [String: AnyObject] {
// Process remote notification in the view
let main = window?.rootViewController as! ViewController
main.initialNotification = aps
}

return true
}
import UIKit

class ViewController: UIViewController {

var initialNotification : [String : AnyObject]?

override func viewDidLoad() {
super.viewDidLoad()
requestNotificationAuthorization()
}

override func viewDidAppear(_ animated: Bool) {
if let app = initialNotification {
let alert = UIAlertController(title: app["category"] as? String, message: app["alert"] as? String, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}

}


}
iOS Alert notifications
iOS Alert notifications
override func viewDidAppear(_ animated: Bool) {
if let aps = initialNotification {
processNotification(aps: aps)
}
}

func processNotification(aps: [String : AnyObject]){
let alert = UIAlertController(title: aps["category"] as? String, message: aps["alert"] as? String, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func application(
_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler:
@escaping (UIBackgroundFetchResult) -> Void
) {
guard let aps = userInfo["aps"] as? [String: AnyObject] else {
completionHandler(.failed)
return
}
let main = window?.rootViewController as! ViewController
main.processNotification(aps: aps)

}

Creating Local User Notifications

extension UIViewController {    func userNotification(message: String, title: String, count: Int){
//creating the notification content
let content = UNMutableNotificationContent()
content.title = title
content.subtitle = ""
content.body = message
content.badge = count as NSNumber
//getting the notification trigger
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
//getting the notification request
let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
//adding the notification to notification center
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

func clearNotification(){
UIApplication.shared.applicationIconBadgeNumber = 0
let notifications = UNUserNotificationCenter.current()
notifications.removeAllPendingNotificationRequests()
notitications.removeAllDeliveredNotifications()
}
}

Full Project Sample Code

Programming from the past century. Worked with many programming languages and software development tools for desktop, web and mobile. https://fraigo.github.io/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store