Updated to work with Xcode 13 and Swift 5.
The UserNotifications framework was introduced with iOS 10 and has been designed to work with iOS, tvOS, and watchOS, and replaces UILocalNotification from the UIKit framework. UILocalNotification and other variants were deprecated in iOS 10.
If you want to send a notification to the lock screen of an iPhone, using the UserNotifications framework is now the way to go.
In this tutorial we’ll look at how to get a basic notification on to the lock screen. In the next tutorial, we’ll look at all the other parts that we do not cover here such as being able to put a notification on screen based on location; without using the CoreLocation framework, and we’ll also look at how to handle specific notifications so that we know which one was tapped or swiped.
Set up a Single View Application
Let’s begin by creating a single view application which uses Swift as the language and SwiftUI as the interface. You might want to call it Notifications, for example.
When created, open up ContentView. Here we’ll add just a single button which will be used to trigger a local notification 5 seconds after being tapped.
struct ContentView: View {
var body: some View {
Button("Send Notification in 5 Seconds...") {
print("Done")
}
}
}
In the code above we see the full ContentView. In the body we declare that we have a button that has the text “Send Notification in 5 Seconds…”, but at the moment, tapping that will just print Done to the console.
Now move to AppDelegate.swift. In the didFinishLaunchingWithOptions method, add the following lines, just before the return true line.
let centre = UNUserNotificationCenter.current()
centre.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization
}
On line 1 we create a constant called centre, and get the singleton user notification object.
On line 2 we need to request authorisation from the user to use notifications. The options: are of type UNAuthorizationOptions of which there are 4 types according to the documentation. These are .badge which provides the ability to put a number in a red circle on the icon. .sound is for the ability to play sounds when the notification is delivered. .alert provides the ability to show alerts, and .carPlay is used if notifications are to appear on CarPlay. In the code above we will use just .alert and .sound.
After the options we have the completion handler which is a closure which contains a Bool we call granted, and an Error called error.
Where the comment is, we can put some code if we are to adjust settings within our app based on the user allowing or declining the request to send notifications.
Moving back to ViewController.swift we can add the following code (most of this is taken right off of the documentation as it’s the easiest way to get started):
@IBAction func sendNotificationIn5Seconds() {
let centre = UNUserNotificationCenter.current()
centre.getNotificationSettings { (settings) in
if settings.authorizationStatus != UNAuthorizationStatus.authorized {
print("Not Authorised")
} else {
print("Authorised")
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "This is the title", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "The message body goes here.", arguments: nil)
// Deliver the notification in five seconds.
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
// Schedule the notification.
let request = UNNotificationRequest(identifier: "FiveSecond", content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request, withCompletionHandler: nil)
}
}
}
Line 2: We get the singleton object for the UNUserNotificationCenter.
Line 3: We call getNotificationSettings. It accepts just a closure as an argument of which a UNNotificationSettings object is provided. We can call this settings. What we are doing here is checking if notifications can be sent. If not, it will be highlighted in “settings”.
Line 4: We use the settings to check the authorizationStatus property to see if the app is authorised. In this instance we are checking if it is !=. If not, a message in the console will appear to indicate that the user either declined notifications, or that they switched them off in the Settings app. At this point you might consider informing the user that in order to receive notifications, then need to reenable them.
Line 8: This is where we essentially copy and paste in the example code from the documentation. We first get a UNMutableNotificationObject object.
Line 9 and 10: We need to add a title (as an NSString) as well as a body as an NSString to the UNMutableNotificationObject we created.
Line 13 and 14: We set the sound to be played and then set the trigger which has a timeInterval where you specify a number in seconds. In this instance, it’s 5 seconds with no repeats. There are several types of trigger we can use. We opted for the UNTimeIntervalNotificationTrigger for this particular example, but the other types include UNCalendarNotificationTrigger for specifying a particular date and time rather than just a length of time in seconds. Another is UNLocationNotificationTrigger which is based on coordinates and a region which is set up with a radius so that it acts like a geofence. A few other types of trigger exist of which some will be covered in the next part.
Line 17 – 19: A request is created with a name, the content, and the trigger. We then call add, and pass in the request.
At this point you can run the app, tap the button, close the app out and switch off the screen on your phone. A few seconds later you will get a notification.
In the next tutorial we will cover more of the features such as changing the sound, using location to trigger the notification, amongst other things.
The project can be downloaded here.
Leave a Reply
You must be logged in to post a comment.