From the course: iOS and watchOS App Development: Notifications

Check user permissions

From the course: iOS and watchOS App Development: Notifications

Start my 1-month free trial

Check user permissions

- [Instructor] This pizza app is all about notifications. We should explain that to the user if they fail to give permissions. If permissions are not granted, I'll post an alert to ask for them. Otherwise, I'll schedule a notification. So let's go to the view controller, head up to the schedulePizza action which you'll find right here. Now permissions matter most when you add the notification. I'm going to check the status using the getNotificationSettings method. It only has a closure with a parameter settings so just type in this. We get UNNotificationCenter dot and then we get current and now we're going to getNotificationSettings and it's got a completion handler so we'll do that. That gets us our closure and that gets us the notification settings we're going to call that settings. And then we're in the code here. Now settings has a property authorization status which I'll assign to status so let's make that, let status = settings.authorizationStatus, there it is, like so. So I'll check the status for not being authorized, add this if status == .denied there's another status I may want which is that it's not determined yet and so I'm going to do status == not determined with an or on there and there's notDetermined. And if this is the case where I've got a denied or notDetermined, I'm going to put an alert for the user. Now alerts since I'm going to using a piece of UI must run on the main thread so I have to execute it here in the correct thread and so I'm going to put a DispatchQueue.main.async and then inside that closure I'm going to put in self.accessDeniedAlert. And if that is all true, then I'm going to put a return after that so that I'm going to pop myself out of here, okay. So that clears me of all denied and notDetermined statuses. Everything else, I'm going to go ahead and set up a notification. I actually have one already which I added to the code for you so you can start playing with them and that's the introNotification so you can type in self.introNotification to get that up. We're going to do this again in the makePizza so I can just take all this code I just wrote, copy it, and I have to do it down here in makePizza so I'm just going to paste it in there like so. This is the basic structure I use for permission checking. Checking for permissions this way makes it easy to deal with changes by the user in permissions and respond immediately to those changes. However, since the closure is running in another thread, make sure you code your notification within the closure. If you try to code outside this closure, the permissions will not be accurate.

Contents