Counting Steps Using HealthKit in SwiftUI App

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
when the app is launched for the first time you will see that it asked for your permission so that you can allow the app to read the steps data I'm just gonna go ahead and say turn all categories and now I'm giving the app the permission to read my steps data I'm also going to say allow vacation it will display the data for the last week make sure that you are running the application on a real physical device or else you will not be able to get the real data from the health kit so this is the app that we'll be building in this section alright so let's go ahead and get started in order to initialize the health kit or the edge k store we will have to go ahead and import the health kit framework so let's go ahead and do that import health kit great now if you want to initialize the HK health store which is going to give you access to all the health-related data you can go ahead and create an instance right inside the content view you can do that but I'm going to do a little bit differently I'm going to create my own custom class I will call it health store which will be responsible for doing any operations related to the HK health store so let's go ahead and create a brand new class I'm going to go ahead and add a new file this will be a simple surf file let's go ahead and add a new file and I will simply call this a health store the whole point of health store class will be to wrap around all the features of the HK health store so I will go ahead an import health kit and going to go ahead and create health store class now this class will have the instance of health store so health door which is of type HK health store keep in mind that health store or HK health store over here is the way it's going to provide you on the features all the functionalities that you want to access like accessing your data accessing the number of steps writing the number of steps exiting X surfing anything related to health you can use HK health store for that now I do want to initialize the HK health store whenever I create an instance of health store so let's go how to do that I'm going to go ahead and create an initializer and in the initializer first I'm going to check that if the health data is even available or not this can be done by a simple F check if HK health store thought is health data available if it is available on this particular device then we can go ahead and create an instance of the HK health store to make sure that you are performing this check its health data available or not because if you're not performing this step then you might try to access the health store or the CK health store and at the end it might throw an exception saying that hey I'm not even initialized alright so now we have created our class health store we can go ahead and use it in our content view so I'm going to go to my content view and inside the content view I'm going to go ahead and create a private variable so private vark health store and we are going to use the health store the one that we have just created so it's just a simple wrapper and inside the initializer for the content view in it I can go ahead and create the health store so health stork equals two health store the health store itself is going to initialize the HK health store as you can see over here so this part will at least initialize the hell store but if you try to run the app it's not going to do anything and the reason it's not going to do anything is that we haven't really requested the permission from the user that hey can we even access the data that is inside your phone so we will have to make sure that we are requesting either read data or write data or write access or read access or even both if we want to access the data which is health-related so let's go ahead and learn about that in the next lecture so let's talk about that how we can request access from the user that hey we want to read the health related data or we even want to write health related data the first thing you need to do is make sure that your info dot plist file contains the key it's necessary to run this app and this is the health related information so two keys that you will need is n s health share usage description and NF health update news H description so I'm going to go ahead and add the first key and I'm going to go ahead and type some description and for simplicity sake I'm just going to say this app requires to share or access to access your health data and I'm just going to copy this so I can use it again for my separate key the second that I want to add is the NS health of data usage description so let's go ahead and add that also and I'm just going to use the same exact thing obviously in your actual application make sure to write a very descriptive message of why you want to access the health related information or share the usage or update the usage and description for the app after making this change we can go back to our health store which is a wrapper around CK health store inside the health store class we are going to implement the request authorization function so let's go ahead and implement this function request authorization and it's going to take a completion handler this is our own custom function so we can pass in anything we want basically we want to create a closure that will be fired whenever the request for authorization is completed and that closure is going to give you access to either success or false based on this boolean value success if well the authorization was successful and failure meaning false if it was failed it was not authorized before asking for authorization we also have to specify well what exactly are we trying to get what kind of data are we trying to authorize because there's so much stuff healthy it can do and what we are trying to get a step count data so we have to create step type this will be H K quantity type so select the H K quantity type dot quantity type for a particular identifier which is H K quantity identifier dot steps count you can see that the H K quantity type of identifier does have a lot of different things that it can keep track of but we are only interested in the step count so I'm just going to get the step count part now once we have the step count we can go ahead and create our get access to our health store we already have the health store so I'm just gonna say guard let health store equals two cells dot health store so basically we're simply just unwrapping this else we will go ahead and return the completion block with the value false we are simply unwrapping the health store so that we can get access to unwrapped version of the health store now we have the health store we can call request authorization so health store dot request authorization from here so let's go ahead and call request authorization to share now over here the first part over here is to share meaning that if we want to write the data and we're not really interested in writing any kind of data so I'm just gonna pass in an empty array the second part is do I need to or do I want to read the data and yes that it's true because I actually do want to read the step type data so I'm just gonna pass in step type and the final thing is the completion which is going to be success and error now finally I can go ahead and call completion passing in success and that's it let's go ahead and build this now we have to make sure that we call a request authorization inside our content view so let's go ahead and jump into our content view and inside the content view we can call this whenever the view actually appears so that means we can implement the on appear function and inside the own appear first of all we can go ahead and unwrap health store so health store equals to health store once it is unwrapped we can go ahead and call health store dot request authorization so let's go ahead and call it function request authorization if they're going to give us a completion which will be success success will either hold the value true or false depending on if the authorization was successful or not and once we have that we can do something else now as I mentioned earlier in order to run this application successfully you have to run it on an actual device so let's go ahead and run the app and hopefully when we run the app it is going to ask us authorization that hey do we want to share or read and write access to this app we want to give the reader not access to the app and you will see the access page being displayed so let's go ahead and run the app so I'm going to press the play button this is going to run the app on an actual food this is a physical phone and it didn't really do anything I mean it didn't really ask for any authorization nothing and if I go back to my code I will see this big error message being displayed you can see that it's saying that missing apple.com developer health care entitlement so we still need to refer we still need to add the capabilities for our project to use health care which we haven't done so let's see how we can do that I'm going to go to my actual target which is just walking the project and I'm going to go to the actual iOS target because that's where I'm running and then select signing and capabilities now I'm going to click on this plus button and in the plus button we can go ahead and search for health care because that's the module or framework we want to add or the capability we want to add let's double click on this and now basically what's going on is that Apple is signing our provisioning profiles and is creating entitlements so that our application can now use healthcare data with this change in place let's go ahead and run the application again and we'll see that this time after ending the capabilities when we run the app it actually gives us this nice health access page where it tells us that hey do we want to give access to this just walking app to read the data and I can go ahead and click on the steps or I can just say turn on all the categories so turn on all there we go and I will say allow and then it goes away and I said that's how you will give access to the actual app that is trying to access any health cakes data and once we have given access to the app so that it can read the data from the phone the next step would be to find out that how we can calculate the steps so let's go ahead and learn about that in the next lecture all right so our next step is to calculate the steps I'm going to jump into health store and going to implement a function which will be called calculate steps so calculate steps this is going to take in a completion Handler and it is going to be returning us a HK statistics collection now what is HK statistics collection basically every day it's going to calculate steps because that's what you want but we can also calculate some other stuff like swimming and workouts and all those kind of things and it is going to give us statistics collection object which contains which we can enumerate and we can get access to every single day so if you're saying that hey I want to access or I want to get the statistics for the last week like seven days ago we can get the collection we can enumerate it and we can get every single day we can get out the number of steps that we took okay so calculate steps first of all we need to tell our statistics collection or whenever we are trying to query these steps that what kind of thing that we are after since the HK health store can allow you to access many different kind of things like swimming data bicycling data workouts this and that we are saying that hey we're only interested in steps so that's why we're going to say the HK quantity type quantity type is step count we're only interested in step count next we need to define the start date so I'm just gonna say a start date and I'm gonna say calendar so where should we start should we start from yesterday till today should we start from a day ago two days ago three days ago two weeks ago a month ago I'm just gonna go ahead and say one week ago so seven days ago so date and we can say over here by adding there we go this one and let's see which one we're going to use by adding a date component and that date component will be day two or the value in this case and the value that I'm going to add is minus seven which means that we are going back seven days and the date till current date so basically a week ago all right next up is we want to get the something call the anchor date the anchor date and the anchor time is more important is when will your day actually starts or what time your day actually starts so that is called the anchor date and we can easily find out the anchor date so I'm just going to copy some code over here what I'm doing is I'm just trying to extend the date so we can just put it right here that's perfectly fine but it will be much better if you put this inside a different file Monday at 12 a.m. so if you if I call Monday at 12 a.m. function I will get that particular anchor date which basically means Monday at 12 a.m. so I'm going to go ahead and say let anchor date equals to date dot Monday at 12 a.m. so basically our day will start at 12 a.m. Mari and we are interested in calculating daily so I'm just gonna go ahead and create another variable daily and I will say date components and I'm gonna go ahead and ask day which will be one correct now I can use something called HK or healthkit query dot predicate for samples so I'm just going to create a predicate variable and I will say HK query dot predicate for samples so example basically means that it's going to tell us this admittedly the predicate or the search query that we're building and this is going to allow us to access the samples the sample data from the start date source car date to the end date which is today whatever today is and we can go ahead and also put strict start date this means that the sample must fall within the time period now in order to perform this query we have to use something called HK statistics collection query and you'll see that a lot of different arguments should go inside this correct so let's go ahead and fill this out the first argument is the quantity type and we are looking for quantity type which is of step type so the step type can just go right there so let's go ahead and and do that there we go up step count or step type quantity sample predicate well luckily for us we also have the predicate which we created a line number 37 so we'll pass in the predicate some sort of the options you want to pass him you have many different options but what we want is accumulate cumulative sum so I'm just gonna pass in the cumulative sum which basically means that maybe one day you had your iPhone in your pocket and you were not wearing the watch so the steps were calculated using your iPhone but the next day you went for running and you were reading your watch and you were not carrying your iPhone so the steps were calculated using the Apple watch so cumulative sum basically means that we want to calculate it using the iPhone plus using the watch Anchor date we're just going to go ahead and pass it and credit interval components daily because we are interested in basically calculating it daily now this is going to return you educate statistics collection query which we want to store so I'm just going to go on the top over here and I'm going to go ahead and create a variable query which is of type HK statistics collection query now like when whatever this returns I can simply assign it so I can say query equals to something all right now finally I can go ahead and create the actual callback handler which is initial results handler the initial results handler is going to get fired whenever we execute the query now you can go ahead and do it get if let and all that stuff if you want that's perfectly fine now this is going to return you that query so I'm just gonna say query and it's going to return you scat tip sticks collection so I'm just gonna copy it it's a long variable name I'm just gonna give it so I'm just gonna call the statistics collection and the error if there are any errors once we have the statistics collection we can go ahead and fire our completion passing in the statistics collection now right now it's not really going to do anything because even though we have created a query we have not really executed it so let's go ahead and do if let health store equals to health store and also let query equals to self not query I can go ahead and execute health store dot execute query and passing in the correct perfect so this means that if we call now our calculate stats is going to say that hey we're interested in step count we're going to create a start date anchor date daily because we want to get the steps calculated daily the predicate which is more for searching which will start from start date and end date we create the edge give statistic collection query and then we execute the curry alright and we should we call this well we should call this inside our content view when we are authorized so let's go ahead jump into our content view you can see that in the content view we can check over here that if it was successful then we can go ahead and say well at this point we can actually call health store dot calculate steps so calculate steps and this is going to return you statistics collection so statistics collection in and we can unwrap statistics collection because it is going to be nullable so I'm just going to say if let step dipsticks collection equals to statistics collection and then over here I can update the UI or the user interface but before I do that I do want to see that what exactly is inside statistics collection if there is any object inside there so I'm just gonna go ahead and just simply print it out this is going to give us a little bit of indication that there is something inside the statistics collection alright now let's go ahead and run this and once the app is running we can go back to our output window and we can see that it is going to give us hopefully it will print out the object content it's not really going to display anything on the screen it's just hello world now if you go back you can see that at least it is printing it now it's not nail or anything like that so this is an indication that statistics collection object deaths contain something but we still have to get this thing out we I mean this object we still have to iterate this object and we should be able to get the steps and also the date on which the steps were actually taken so let's go ahead and do that in the next lecture in the last lecture you learn about how to calculate the number of steps and it gives you the number of steps in a form of HK statistics collection and we're simply printing out the collection on line number 29 but what we want to do is we want to access the steps and we also want to populate our own custom model so let's go ahead and do that right inside the content view I'm going to create a separate function this will be a private function we will call this update UI from statistics and we are going to be passing the statistics collection so I'm just going to create a variable named statistics collection which will be of type HK statistics collection now in order to calculate the number of steps we can use statistics collection dot enumerate and you'll see that in order to enumerate we have to provide the from date to date and then it is go to give us these statistics so let's go ahead and calculate the start date the start date is seven days ago so we can use the same exact code the end date is today or whatever date is right now and we can simply pass in the start date and end it and we can get the statistics collection associated with that date so I'm going to go ahead and pass in the star date I'm going to go ahead and pass in the end date and this is going to give me statistics so I'm just going to call it statistics and this will be the pointer for stopping the enumeration great now inside enumeration we need to access the number of count so count this is the number of steps statistics dot some quantity dot double value for dot count basically we're looking for the count the number of steps and the question is where should we store these steps for that we're going to create our model so I'm just going to create a new group and I will call it models inside the model I'm going to go ahead and create a new surf file and I will call it step the whole point of this model is to associate steps and the date now if we were creating a mvvm application meaning the MDM design pattern I would create a view model but we are simply going to create a simple model that we can use so struct step now since we want the steps to be you've displayed in a list I'm going to make sure that I am conforming to identifiable next up we can had a create a field called ID and we can initialize it with UUID we will create another property called count which will be the number of steps and you can use a double over here or you can use int as completely up to you I'm just going to use int and finally we're going to go ahead and create a date instance which is the start date or the date for those number of steps now let's go back to the content view and inside the content view we should now be able to get the steps and create our step instance I'm going to go ahead and create a step instance of a college step and you can see that I need to pass in the count as an integer so I'm gonna go ahead and pass same account and if the count is null or something we're just gonna pass zero and a particular start date which I can also get from statistics dot start date perfect now I need to store this step somewhere and for that I'm going to go ahead and create another variable this will be a state property so I'm gonna go ahead and save state private VAR steps and this will be of type step and we can also go ahead and initialize this to be saving step instances now keep in mind that since we are not using the mvvm design pattern I'm using this state property wrapper right over here if I was using mvvm design pattern then I would most probably create a view model that will have the steps as a published property wrapper or observable object now let's go ahead and add the steps so steps toward append a new element which in this case is step perfect so now finally we have to make sure or that once we are receiving the steps which is right over here after calculating the steps we have to call the update UI from statistics so instead of the print let's go ahead and call that function and pass in the statistics collection perfect in the next video I'm going to show you that how you can display the steps on the screen so let's go ahead and check it out that how we can display all the steps coming from the health kit in a list control all right so now let's go ahead and finally see that how we can display the steps that are coming from the health kit we have already populated the steps inside our steps array and now we can go to the body property which is a render function and remove the text and substitute it by using a particular list so list steps ID property that we are going to be using will be the ID and we can use the ID property because steps is an array which contains objects of type step which contains the ID property we're gonna say step in and finally we can go ahead and display these steps so I'm just gonna say text and we're going to display these steps using a string interpolation step dot count apart from the steps you can also display the date associated with the step so since we want to display the date underneath the number of steps I'm going to go ahead and ramp the text into a vertical stack there we go and for the date I can simply say step dot date and the cool thing is that I can also use the style and specify that it will be of type date and we can also provide a little bit different opacity so opacity will be that says half 0.5 now once again you do need a real device to run this application so that the healthkit can find the number of steps from your actual device so let's go ahead and run it and hopefully we'll be able to see all the steps being displayed on the actual device this is our actual device and we're just waiting for the applications to start and there we go we can see all the different steps from a week ago so July fix till July 13th we can go ahead and organize it a little bit more better we are using a reefs tank we can use the alignment of the V stack and we can say leading by the way this feature of putting the or formatting the data is available in iOS 14 and I am using the hex code 12 beta version but I think all of the code can be written for any version like the previous version of iOS except for this part the date part the other thing that I want to do is I want to wrap everything around with a navigation view so I'm going to go ahead and start a navigation view right over here on the top you can say navigation view we're going to wrap the list around with the navigation view there we go and we're going to also say the navigation title and I'm just going to put the title to reach us walking which is the name of our app now let's go ahead and run the app again making sure that we are running it on an actual device and now when we run we can see the navigation bar being displayed and all the steps pretty cool right so in this section you have learned that how you can integrate your surf UI application where the hell kid and to get the data and to be displayed in a list control I really hope that you have enjoyed this video and hey don't forget to download the source code attached with this lecture in the resources section thank you so much if you liked this video and want to support my channel then the best way would be to check out my courses on udemy I have a brand new quote which is so if you like decorative interfaces for any Apple device this is the most comprehensive course available on udemy you can actually see that this is around 17.5 hours the longest course and the most comprehensive complete course on 30 y anywhere you can see that we start with creating and combining views building lists and navigation then we even dive into the mvvm design pattern learning how to use mvvm design pattern to create our next surf UI applications i'm also covering the core data integration and also surf recipes which includes building a rating view downloading images and now i'm also covering all the six 2.0 changes you can see there are a lot of changes coming up we are already over an hour of changes and I keep on adding new things the best way to get this course is check out the description of YouTube and in the YouTube description you will not only find a link to the surf UI course but you will also find many different links for all of my courses and I would really appreciate if you want to show the support then check out my other courses I just released another course on vapor 4 which allows you to write Swift application or api's using Swift on the server and on the cloud which is an amazing course so definitely check that out I really hope that you have enjoyed this video thank you so much for your continuous support
Info
Channel: azamsharp
Views: 7,333
Rating: undefined out of 5
Keywords: swiftui, swiftui ios 14, ios development, xcode, swift language, swiftui tutorial, healthkit ios
Id: ohgrzM9gfvM
Channel Id: undefined
Length: 37min 33sec (2253 seconds)
Published: Mon Jul 13 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.