This workshop will be retired on May 31, 2020.
iOS Local Notifications18:55 with Josh Timonen
In this workshop, learn how to handle Local Notifications in iOS.
[MUSIC] 0:00 Hi there. 0:04 My name's Josh Timonen, an iOS developer. 0:05 Many iOS applications need to notify users of an event, whether the app is open or 0:08 closed, or in the background. 0:14 For example, it could be an alarm, a new message from a friend, or a 15% off sale. 0:16 To achieve this, iOS uses local and push notifications. 0:23 In this workshop, we're going to focus on local notifications, 0:28 which aren't talked about quite as much as push notifications. 0:32 Here's the difference between the two. 0:36 Push notifications are created and sent remotely from a server. 0:38 Local notifications are created and registered by our app and 0:43 then triggered by the operating system at a specified date and time in the future. 0:47 They work in very similar ways with very similar structures and methods. 0:52 So learning how to use local notifications will equip us with most of the knowledge 0:57 needed to handle push notifications as well without needing a remote server. 1:00 Local notifications could be used in a custom alarms app featuring your own 1:06 custom sounds, or perhaps a workout app that notifies the user when to 1:10 start working out, and then when to change exercises. 1:15 Local notifications are great for 1:19 any apps that need to notify users at known intervals or specific times of day. 1:20 We'll learn to use local notifications to trigger app behaviors, add a batch number 1:26 to our app icon, play a sound during a notification, send our app data, and 1:31 handle the notification one way when the user is in the app, and 1:37 then a different way when they're outside of it. 1:40 Okay, so let's get started. 1:43 First, let's open Xcode and create a single view project. 1:45 We'll call it LocalNotificationDemo. 1:52 Open the AppDelegate implementation, or .m file. 2:06 Starting in iOS 8, 2:11 we need to request permission from the user to display notifications. 2:12 We need to create a UI user notification settings object with the types 2:17 of notifications we want to use. 2:22 For this demo, we're going to use all three, badge, alert, and sound. 2:25 We'll do this in did finish launching with options. 2:31 We create this object with the class method UIUserNotificationSettings, 2:35 settings for types, and then entering in the types separated by the pipe 2:40 [BLANK_AUDIO] 2:44 We'll also leave categories, nill. 3:16 We then call registerNotificationSettings on 3:19 the application with this notificationSettings object. 3:22 This will present an alert to the user requesting to use notifications. 3:25 For this workshop, we're going to assume the user will always click yes. 3:30 There are callback methods we could be listening for that would tell us 3:34 the user's choice, and we could branch our app's behavior accordingly. 3:36 We'll also be only building for iOS 8. 3:40 If we needed to support iOS 7 or 3:43 earlier versions, we'd need to do some additional code branching. 3:45 Now, let's launch the app in the simulator by hitting the Play button or 3:49 using the hotkey Cmd+R. 3:53 [BLANK_AUDIO] 3:55 We'll see the system alert asking for permission. 4:00 Hit OK. 4:03 Back in Xcode, in our appdelegate.m file, we'll create a new method right below 4:05 the didDinishLaunchingWithOptions method named generateLocalNotification. 4:10 We'll then call this method inside didDinishLaunchingWithOptions, 4:15 right before return yes 4:19 [BLANK_AUDIO] 4:20 This will call our method and 4:26 the code we're about to write as soon as the app is launched. 4:27 In our generateLocalNotification method, 4:30 we'll create a UI local notification instance named localNotification. 4:33 [BLANK_AUDIO] 4:38 Now that we've created it, we'll want to set some of its properties. 4:52 First, we'll set it's fireDate property, which is an NSDate object. 4:56 [BLANK_AUDIO] 5:00 This will be the time that the notification is triggered. 5:06 Let's trigger this notification 15 seconds after launching. 5:10 So, we'll create an NSDate with initWithTimeIntervalSinceNow:15. 5:15 This creates an NSDate 15 seconds into the future from when this code is run. 5:22 Next, we'll set the alert body property to an NSString. 5:27 This will be the text displayed on the notification when the user is 5:31 outside the app. 5:35 [BLANK_AUDIO] 5:36 Let's set it to My First Local Notification. 5:40 Next, we schedule the notification with the application. 5:47 We do this by calling UIApplication, SharedApplication, 5:51 scheduleLocalNotification, localNotification. 5:56 We've now created and 6:03 registered a local notification that will trigger 15 seconds after our app launches. 6:04 Now, let's launch the app in the simulator. 6:10 [BLANK_AUDIO] 6:13 Once the simulator is open, go to the top menu bar and select Hardware > Home. 6:19 This simulates hitting the Home button on the phone. 6:25 There's also a hotkey for this, Cmd+Shift+H. 6:28 [BLANK_AUDIO] 6:31 Within a few seconds, 6:35 we'll see the notification appear at the top of the screen with our custom message. 6:36 And tapping this notification takes us to our app. 6:41 So now we've generated our first local notification. 6:45 Next, let's badge our app icon when this notification is fired. 6:49 On our localNotification object, 6:56 we set the property application badge number to our desired integer. 6:58 Let's say three. 7:03 Now, if we build and run our application, 7:05 we'll again simulate tapping the Home button to background the app. 7:07 [BLANK_AUDIO] 7:11 We wait a few seconds and our notification fires. 7:21 We can also see that the app icon is now badged with the number three. 7:27 We can set the sound name property on our notification to 7:34 the standard notification sound with UILocalNotificationDefaultSoundName. 7:37 If we want to use a custom sound file, 7:45 we need to first add the sound file to our project. 7:47 We'll add this sax.aif file. 7:53 Make sure we add the file to our local notification demo target, then click OK. 8:03 Now we can set the sound name to sax.aif, and this will play the sound with 8:09 the notification when it's presented from outside the app. 8:13 If we launch the app, simulate the Home button and background it, then wait for 8:17 the notification to fire, 8:22 we'll hear our custom sound when the notification is fired. 8:23 [BLANK_AUDIO] 8:27 [MUSIC] 8:36 Let's also add some basic data to our notification in a dictionary structure. 8:40 We're going to keep it simple here, just a single key and value. 8:46 We assign it to the userInfo dictionary on the notification. 8:51 We're just going to set an ID to the number 42. 8:56 [BLANK_AUDIO] 9:00 When we've received the notification, we read in this data and 9:05 do something with it. 9:09 Next, let's take a look at how local notifications are handled differently when 9:11 triggered from outside the app, or inside it. 9:15 To trigger a notification from outside the app, 9:18 the user needs to tap the notification bar across the top of the screen, or 9:21 swipe across the notification on the lock screen. 9:25 When this happens, a method is called in the app 9:28 delegate called applicationDidReceiveLocalNotification. 9:31 If the user is inside the app when the notification is triggered, 9:36 this method is triggered automatically with no action needed from the user. 9:39 So let's set up this method in the app delegate. 9:43 We want to set up some branching here to behave differently if 9:57 the user was inside or outside the app. 10:00 We want to check the application state property. 10:03 [BLANK_AUDIO] 10:06 If UIApplicationStateActive, then that means that the user has had the app 10:16 open when the notification was triggered. 10:20 Let's create a method called takeActionWithLocalNotification that 10:25 accepts a UI local notification object. 10:29 Inside this method, we can then access the notification's user data dictionary and 10:46 get that ID we set. 10:51 We'll assign it to an NS number called notification ID. 10:58 Then, let's just present an alert telling the user we 11:04 are viewing the notification with this ID. 11:07 We'll use the new iOS 8 UI Alert Controller class to do that. 11:11 So again, if you need to support iOS 7 or earlier, you'll need to branch for that. 11:15 We'll create an alert controller object with the title Action Taken, and 11:20 the message that we are viewing notification, and 11:25 then the notification ID number. 11:29 We'll set the preferred style to UIAlertControllerStyle alert. 11:31 [BLANK_AUDIO] 11:36 So this code just presents an alert with a string in 12:13 the message field that will display our ID. 12:16 Of course in your app, you'll probably want it to do something more, but 12:19 this at least lets us see that an action has been taken in the simulator. 12:23 We then present this alert controller just like we'd present a view controller 12:27 with self.window.rootViewController, presentViewController, 12:33 alertController animated:YES. 12:39 [BLANK_AUDIO] 12:42 So if the application receives the local notification from outside the app, 12:48 we just want to call this method, 12:52 takeActionWithLocalNotification, passing in the notification. 12:54 So, if a user was outside of the app, 12:59 then taps on this notification the didReceiveLocalNotification method will be 13:02 triggered, and we just want this action to be taken immediately. 13:06 There's no risk of interrupting the user here, so 13:10 we just call our takeActionWithLocalNotification method. 13:13 If the user was inside our app when the notification was triggered, 13:17 we need to first tell them that the notification has happened and 13:21 allow them to choose to take the action or ignore it. 13:24 First, we'll create a basic alert controller with a title Notification, and 13:28 the message set to the notification's alert body. 13:32 [BLANK_AUDIO] 13:35 Next, we'll need to create two UIAlert action objects. 14:02 One to ignore and one to view. 14:06 First, we'll create the ignoreAction with the UIAlertActionClass method. 14:12 ActionWithTitle ignore, Style, UIAlertActionStyleCancel. 14:17 Then handler, which is our completion block. 14:28 Nothing's really going to happen in this completion block, so 14:35 we will just do an NSLog, with the text ignore. 14:37 Similarly, we're going to create a viewAction object with the title View. 14:46 [BLANK_AUDIO] 14:51 And inside its handler block, 15:11 we'll call the takeActionWithLocalNotification method. 15:12 We're also setting its style to UIAlertActionStyleDefault. 15:19 Next, we add these actions to our alert controller object with 15:23 the method addAction, passing in our 15:27 UIAlert actions. 15:31 Then, we present our alert controller from self.window.rootViewController, just 15:40 as we would in modal view controller, again, with presentViewController, 15:45 alertController, animated:YES, and then an empty completion block. 15:49 Now let's test the notification both ways. 15:56 First, we'll test triggering it from outside the app. 15:59 So, we'll launch the app in the simulator, 16:03 then background the app, and wait for the notification to trigger. 16:07 [BLANK_AUDIO] 16:13 When we see it appear at the top of the screen, tap it and we'll see our 16:22 application launch, then show us the alert stating we are viewing Notification 42. 16:27 We have successfully taken this action. 16:32 You'll notice though, that our alert doesn't have an OK button. 16:35 So let's go back to our takeActionWithLocalNotification method in 16:39 the app delegate. 16:42 And we'll add an OK action to that alert controller before presenting it. 16:47 [BLANK_AUDIO] 16:51 If we relaunch the simulator, then background the app again, and 17:19 tap on our notification once it fires, we'll now see that we have an OK button. 17:23 [BLANK_AUDIO] 17:28 [MUSIC] 17:38 Okay, so now let's relaunch the app in the simulator, and 17:44 this time let's stay in the app until the notification triggers. 17:47 [BLANK_AUDIO] 17:51 This time, we see the app presents us with our alert controller asking if we 18:12 want to view or ignore the notification. 18:17 If we tap View, we see our Action Taken notification as expected, 18:20 stating we are viewing notification 42. 18:25 If we relaunch the app again, and wait for 18:29 the notification to trigger in the app, then hit ignore- 18:31 [MUSIC] 18:35 We can see that nothing further happens as desired. 18:37 So now we've learned how to register and handle local notifications. 18:43 There's a lot more we can do with these, and hopefully this workshop serves as 18:47 a good launching point for your own experiments and investigations. 18:50 Thanks for watching. 18:54
You need to sign up for Treehouse in order to download course files.Sign up