How to schedule local Push Notifications in SwiftUI | Continued Learning #11

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome back everyone i'm nick and this is swiffle thinking and again just like the last two videos this video is not technically swift ui related but it is important if you're making a swift ui application and that's why i'm going over it what we're going to cover is local notifications now it's important for beginners to understand the difference between a real push notification and these local notifications now the main difference here is that these local notifications we can actually set up and create within the application ourselves while the real push notifications are coming from a server so just to highlight the difference an example of a local notification might be a notification that occurs every monday or every day at 5 00 pm because when a user opens the application we have all of that data to know exactly when to send all of those notifications but if you want notifications to happen based on other user interactions so if someone liked your picture or someone commented on your picture we don't know when a user opens the app when that is gonna actually happen so for those advanced push notifications we actually need a server and there's a lot more logic involved and we're not talking about that right now we're just going to focus on the local notifications that we can set up ourselves and these local notifications are actually fairly easy to set up and there's three main triggers that we can have on these notifications the first one is time based so we can say notify me one hour from now notify me two hours from now the second one is calendar based and using this we can schedule notifications based on time or date so for example we can schedule notifications that happen every day at 5 00 pm or we can schedule it maybe every monday or wednesday we can also schedule it for maybe every first of the month or every fifth of the month something like that using the calendar and the third and least common way is actually by a location and here we can schedule notifications to happen when a user enters or leaves a physical location when the device actually leaves a location in real life this would be used more for apps that are based on a physical location like a coffee shop app or maybe if there was a destination on your app that you were tracking it's a little less common but we'll still go over it overall these local notifications definitely add a really great user experience to your app without all the complexities of the actual push notifications so if you're a beginner developer i definitely recommend incorporating these into your app starting here and once you're more comfortable with app development then try to tackle the actual push notifications that are coming from a server all right that's enough of me talking let's open up xcode and get coding all right welcome back everyone i'm back in xcode of course and we're going to create a new file for this video let's right click on the navigator create a new file this one will be a swift ui view and we're going to call this local notification boot camp go ahead and click create and as i mentioned this is not technically a swift ui video but adding local notifications is something you're going to do in swift ui apps so i wanted to quickly cover it let's start by setting up our view and it's going to be really really simple we're just going to add a v stack open the brackets actually let's give this v stack maybe some spacing of 40. and let's just start with a single button in here open the parentheses we're going to use the string protocol and let's just make the title request permission let's click enter on the action and we'll leave it blank for a second because we don't actually have anything to request yet and like i've done in the last two videos where we covered sounds and haptics i'm going to create a singleton to create a class that will manage all of our notification requests so to do that let's create a class let's call this notification manager and let's open the brackets let's then add our instance by adding static let instance equals notification manager open and close parentheses this again is a singleton and if you're unfamiliar with these singletons i covered them in detail in the sounds bootcamp which i did two videos before this basically this is a single instance that we're going to use throughout our entire application so that we don't have to keep creating notification managers we're just going to use this one here and now the first thing we need to do before we can actually send notifications is request permission from the user that we are allowed to send notifications so if you've ever downloaded a new app and you get that notification that says this app would like to send you notifications that's what we're going to do right now so let's create a funk let's call it request authorization open and close parentheses open the brackets and to access the notification framework we actually need to import the framework so we're going to type import user notifications at the top and then very simply with now that we have access to this notifications framework we can call un user notification center dot current and then we can call dot request authorization and in here we need to pass in un authorization options so before this let's create those so let's say let options of type un authorization options and we'll say equals and if i press the period here i can see all of the options that i have now only some of these are relevant depending on your app and the environment but we're going to use the three that are most common and usually requested in iphones and ipads and because we're going to use three of them we're going to create an array here so let's open and close the brackets and inside that array let's press the period and we're going to request for the alert the dot sound so that we can get into sound with our alert and a a badge so the alert is the actual pop-up the sound it comes with the pop-up and the badge is i believe the number that we can update on the icon on the home screen so now that we have the the options that we want to request let's take this options and just pass it in here and then in the completion handler we can see that we are getting a bool and an error back so let's click enter on that and this returned bool i'm going to call success and this error i'm just going to call error and now we're not actually going to do anything whether or not this is successful or there's an error but let's just print it out to the console so that we can see that it's working so let's just say here if let error equals error open the brackets so this error is optional and we're just using an if-let's statement to make sure that there is an error so and if there's an error let's just print out uh error and then a colon and i'll just do the backslash open and close parentheses and then we'll print out the error that we just got and we'll say else so if there is no error we'll print success okay so we're not actually doing anything with the success but we're just going to print it out so that we can see if it worked or not so let's test this out and now in our button i just want to call this function so we're going to call notification manager dot instance which is our singleton and then we'll call dot request authorization and now to actually request authorization i believe we need to run it on the simulator so let's take the name of our view here the local notification bootcamp let's copy it i'm going to jump into the app.swift file in our project which is the first file where the app main call is i'm just going to replace the first view with our local notification boot camp so this will be the first view when we load the simulator i'm going to make sure my simulator is an iphone 12 and then i'm just going to click this play button to run it on a simulator all right and now that i have the app open on my simulator i'm going to click the request permission button and we're going to get this pop-up that you've probably seen a bunch of times on apps uh with the name of my app swiffle thinking continue learning would like to send you notifications and you'll see that it says the alert sound and icon badges because that's the options that we added here and then we can allow or not allow these and if i click allow we should get the success printout which we can see here and the cool thing about the request authorization is that it does remember uh the device so if i click it again now we're not gonna get the pop-up it's just gonna print out success because it will remember that you already authorized it i'll note here that if you want to reset this the easiest way is to just delete the app's data from the iphone so i could just close down the app and i'm just going to delete it from my device here and then i will just press run on the simulator one more time and it will just reinstall and when i click it again it sends me back to the original message i'm of course going to allow this because now that it's allowed we want to actually send some notifications so the next function we're going to make is called funk schedule notification open and close parentheses open the brackets and to schedule these notifications we have to create some content first so we'll say let content we'll set it equal to un immutable notification content this is the edible content for notification and i will open and close the parentheses to create a new instance and then on this content we can edit it because right now it's blank so we'll call content dot title i will set it equal to this is my first notification we could then add content dot subtitle and i'll say this was so easy then we can add content dot sound and we can set it equal to the default sound which is which is the definitely the most common and almost always used and lastly we can add content dot badge and if we look at the badge it is actually the number to apply to the apps icon so i'm going to set that equal to one and remember we can add the the sound and the badge and the alert which is the title and subtitle because that's what we requested in our options so we can then actually schedule and request a notification by saying let request equals request equals un notification request and we'll open the parentheses and we have a completion with the identifier content and trigger now the identifier is used more if you want to actually keep track of this content if maybe if you want to save it somewhere to come back to it so that you can cancel it later but for our purposes we're not going to be tracking anything so we don't really care what the id is so i'm just going to create a random id here by using uuid open and close parenthesis dot and let's add the uuid string this will just create a random identifier let's put this on a separate line just to make this a little easier to read here then we need to add some content and we already have our content so we'll just pass it in and lastly we need a trigger and trigger is when we want the actual notification to send now there are three types of triggers we can add there's time calendar and location so i'm going to show you all three of these right now because they're pretty simple i'm going to start with the time so let's say let trigger equals let's start typing in time trigger and it's the un time interval notification trigger open the parentheses and we're going to use the time interval and repeats option so basically whenever we actually call this request and request a notification this time interval is kind of like the delay so if i add here five for five seconds so let's do 5.0 this trigger should go off five seconds after scheduling the request and then we can add the repeats so if we want to repeat this every five seconds send another notification we could set this equal to true i think if you wanted to repeat the time interval needs to be at least one minute um so for right now let's just put this as false so only happens one time with it and that's five seconds from when we schedule it then i'll just take that trigger and pass that in down here as the trigger for this request and then finally we just need to call u n user notification center dot current dot add and then we have a completion here that actually accepts a un notification request click enter on it i'll pass in our request and then this completion handler is actually optional so i'm just going to delete it because we're not going to use it we have a nice little ad request here and the last thing we need to do is call this function from our app so back in our view i'm just going to copy this button and paste it below let's change the text to say schedule notification and i'm just going to change this call here to call dot schedule notification let's click play on the simulator one more time so that it rebuilds and let's test that out i'm going to keep in mind here that my request permission is success we did authorize notifications because if you go to schedule and you didn't authorize notifications obviously they won't work and what i'm going to do is click on schedule notification and then minimize the app because by default notifications only pop up on the device if the app is in the background they don't pop up when the app is actually open so i'm going to click schedule notification i'm going to minimize my app and then about five seconds after i click that my notification should come in and i'm going to click and hold on it just so you can see quickly the notification will have the the title of your app which will probably be much shorter than what mine is right now so if we'll think continue learning on the top left you're going to have your apps icon so we'll look much better than this as well and then we have the title which i set to this is my first notification as well as the subtitle uh which we made this was so easy when this came through it had a sound and that was the sound that we had here and then on the actual icon there is a number one and that is the badge that we set here for number one all right and now if i open the app and i close the app i did notice here that this number does not go away because we need to actually manually remove the badge when we want to so on my v stack i'm going to add a simple dot on appear and open the brackets and every time we view the screen i'm just going to call ui application dot shared dot application icon badge number and i'm just going to set it equal to zero because if we set it back equal to zero this one should go away so if i run it one more time and the app opens as soon as it appears it should set the icon badge back down to zero and here we go all right we did the time let's now do the calendar so i'm going to comment out this trigger i'm going to start typing in let trigger equals i'm going to type in trigger and look for the un calendar notification trigger open the parentheses and we have a date matching and repeats completion this date matching needs date components so let's create those first let's say let date components equals date components open close parentheses and this is just a blank date right now but we can customize it to whatever kind of date components we wanted to have so the most common is setting the hour and the minute so we'll call date components dot hour and this is the actual hour in the day that we want this notification to occur and i believe it's in military time so right now as you can see it is it is 8 24 p.m so this is our 20 i'm going to put this as 20 and then we'll add date components dot minute i'm going to set this equal to uh 26 because it's 8 24 right now we should actually make the date component a variable so this will be a var and these errors will go away and if i end by leaving this right now every day at hour 20 minute 26 this notification will go off so every day at 8 26 p.m this notification would go off i'm going to take the date components and just pass that in and then repeats i'll put it as true so this repeats every day at 8 26 and i'm gonna run my app so now we're using the calendar component and i'm going to click schedule notification which should schedule it to happen at 8 26 i'm going to close my app and i'm going to wait now for the clock to turn to 8 26 and it should pop up with our notification [Music] and there we go 826 and right on time our notification comes through another really common uh modifier here i see is date components dot week day and then you can set this equal to what day of the week you want this to happen and i'm in the u.s so i think weekday starts uh one is actually sunday so uh it is friday right now so it would be uh six i believe and so here i can get a notification to happen every friday at 8 26 or if i wanted to do every maybe monday so i think that's number two we can do maybe minute zero and hour eight so every monday at eight am we can schedule a notification to happen and if you guys look into these date components and press the period here there's a whole bunch of ways we can customize this we can customize this so we can do the first week of every month the first week of every year you can do a whole bunch of really cool things and this just makes it so easy to schedule a bunch of notifications so if you want to do something in your app where you have a notification go through every day every week this is definitely the way to go it's super super easy we've done the time we've now done the calendar and the last way to do it is with a location so i'm going to hit so i'm going to come down here and say let trigger equals start typing trigger and we're going to look for the location notification trigger open the parentheses and this wants a region and repeats and we need a region here and you see we're already getting an error message that cannot find type cl region because we don't have the location framework in our file yet and cl stands for core location so backup at the top where we import our user notifications we can also import core location and i can go down and then here i can say let region equals and we're going to set this equal to a cl circular regions this is a circular geographic region specified with a center and a radius so think about it as if you looked at a map and you put a pin down and then drew a circle around it that's what this would be creating and we will open the parenthesis and we're going to use the center radius and identifier let's put these in separate lines so they're a little easier to read and for the center we actually need specific coordinates to put in here so i'm going to create one more variable let's say let coordinates equals cl location coordinate 2d which is what this type is right here open the parentheses and we need a latitude and longitude so i'm not going to go and actually look up a latitude or longitude you can google new york city latitude longitude or wherever you're trying to use as a location and find that i'm just going to put like 40.00 for now and maybe 50.00 because it's not relevant we're not going to actually test this we're going to then take the coordinates pass it in as the center we can then add a radius and if i hold the option button and click on the radius this is the distance measured in meters from the center point to the edge so if for example my coordinates was maybe that represented a specific coffee store that we're making an app for like a coffee shop well i want the radius to be probably about the size of the coffee shop so maybe uh 50 meters or 100 meters we could put and then the identifier for our purposes isn't very relevant so i'm going to create a random id again so we'll do uuid open close parentheses dot string and we'll just take our region and pass it in here and we'll make this true the last two things i want to set before this trigger is we can call the region dot notify on exit and entry and i'll set these equal to true and then region dot notify on and on exit equals uh maybe false and so basically with this set up here we've set a coordinate and we've we've found a center coordinate which could be like your coffee store we added a region which has a radius of 100 meters all around that center point and then anytime a user enters that region like physically walks into that region we have notify on entry equal to true so this should trigger and then if we wanted a notification to also happen when they leave we could say notify on exit equals true and then this trigger would happen when they come in as well as when they leave so obviously we can't really test this because i'm not walking anywhere i'm just on a simulator but now you do know how to set this up and the last thing i want to show you guys because this video is getting long is just how to quickly cancel notifications because because there could be times in your app where you've scheduled maybe a whole bunch of calendar notifications and when the user opens it you want to just cancel all those and schedule a bunch of new ones so to do that let's create a funk cancel notifications open close parenthesis open the brackets and we'll just call just like we do here we'll call un user usernotificationcenter.current.remove all pending notification requests and we can also say un usernotificationcenter.current.remove all delivered notification requests if we want to if we want to remove these notifications from the notification center on the user's iphone so for example right now we already had a notification come through on the simulator and if i swipe down i can see that that notification is still in the notification center on the iphone even though i already saw it so this would get rid of it here and then this pending one would cancel any upcoming notifications that haven't actually occurred yet then let's just add one more button to our view we'll say cancel notification and here we'll just call cancel notification we can now run it and you are now an expert at scheduling local notifications you can request permission schedule a bunch of them and then cancel them if you ever need to i know this was not really a swift ui video again but if you're making an app these local notifications especially this calendar one are super handy and so so easy to implement i highly recommend using them in your app because notifications is just a very very nice user experience that really makes your app feel professional all right thank you guys for watching as always i'm nick this is swiffle thinking and i'll see you in the next video
Info
Channel: Swiftful Thinking
Views: 2,451
Rating: undefined out of 5
Keywords: SwiftUI local notifications, SwiftUI notifications, SwiftUI how to add notifications, SwiftUI push notifications, SwiftUI schedule notifications, How to add notifications to SwiftUI, How to add notifications SwiftUI, how to add push notifications Swift, How to add notifications Swift, Swift notifications, Swift local notification, Swift push notification, Swift notification based on time, Swift notification based on date, Swift notification based on location, Notifications iOS
Id: mG9BVAs8AIo
Channel Id: undefined
Length: 26min 43sec (1603 seconds)
Published: Fri Apr 09 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.