How to Cache Image Files with Ionic & Capacitor

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up simonix and welcome back to a new quick win today is basically the second part of a tutorial that we last started last week but it's actually also a tutorial on its own because i didn't want to have any dependencies between them um last week we talked about caching your api responses using capacitor or ionic storage and today we're talking about caching files because that is a bit different and we will implement a simple component so we can basically replace just the image text that we used in our application and in the background the component does all the hard work like downloading the file saving the file or retrieving the file in case we need it if you want to access the full quick win make sure you check out the link below and become a member of the ioniq academy if you're not yet so go check it out ionicacademy.com or simply click the link below the video and now let's dive into our image caching component with ionic and capacitor alright so let's get started with today's application we're gonna start with a blank template we're not using the code from the previous tutorial about api caching but i'm sure you can easily combine those two approaches the only thing we need today is a module for components and a new component that we want to build out once you got that in place you can heat over to the app module since we are making http requests we need to inject the http client module and import it into our app module and with that in place we can heat over to the homepage and html and ts and implement the basic um let's say dump functionality or or the default functionality how it usually looks in your application so you might have some products uh some kind of array and you're making http requests to this uh fake store api which returns some images and we want to cache those images uh we're gonna just assign it to our products and we're gonna call this the load products right in the beginning so let's first of all take a look how this in general looks okay maybe we should also implement a little view that could really help um so let's put into a button and ion card ng for uh let p of products and then we can go ahead uh let's just put in an image we're gonna use the product image as source um maybe gonna add a little bit of ion padding because uh always good if it doesn't look too crappy now ion card content and let's bring into the content a bit of uh information from the json just so we see something on the screen with the title and the price okay we got our api now how can we verify what we're actually doing uh we can first of all go to the network tab and let's clear everything and we can also activate image and let's hit load products and what we see we're loading these i think 20 product images now let's remove this the product again and once again we're loading them so if each of them has about a size of 50 uh 20 we're already at one megabyte if i calculate this right and these are pretty small images now how can we improve that behavior of course here it is pretty fast but if we enable some kind of throttling then you know of course the hdp request will be slow but loading the images is really painful and on devices with a slow connection this can really take a lot of time now as we can see some images are coming in but they really take a long time so uh let's move back to node throttling for now and let's see how we can improve that and we can do this with our custom component for the setup make sure your custom component is declared and most importantly oh not that most importantly also inside the export array because only if it's in the export array we can heat over to our page and import the shared components module and that's what we need to do all right now we can heat over to the logic for our component so in general the logic is actually pretty easy uh let's start by defining a little cache folder up here um usually you could also have this inside a service but i didn't want to bring up another file for this tutorial so uh we're just inside doing it inside our custom component that will work as well now we will have a source variable in here which we will set to an empty string in the beginning and because we're doing this we can also take a quick look at our implementation for the html so basically the only thing we want to display in here is an image and we want to use for the image source our underscore source now we only want to display this if our source is actually unequal to an empty string and in the else case we want to display a little loading indicator now we can define this by using ng template oh that was that was interesting but i don't need anything and we got one bracket too much so well me a bit more work now this is how you do it if you're using an ng of else you can define an ng template for the loading you could also have ng of source whatever in here without else different ways using the same and then we're going to put in maybe just for now an ion spinner we can also customize this later um if you now see a red line under this it's most likely because you haven't added the ionic module i already did this up front so make sure your shared component also imports the ionic module since you're using an ionic component in there and now we can go back to our logic and define an input but we don't want to just define an input for the source element because then we are already setting the source um you can already imagine that we are likely changing the image to something like app image and then putting in the source to our image so something like this it's not correctly right now but something like this and if we just take the source input and display it we're going to have basically the same logic like we had before so instead we're going to define directly a setup function for source which basically gets the source we will call this uh image url and that means our cached image maybe we can even use it already because then you can see it in action the selector is the name for our component um so let's use cached image and putting in the source and within here we should now get a lock set source to our image url and let's see if this changes something hopefully it does uh cached image is not a known element well that sounds great we added it to the home module we gave it the name cached image we're using it with cached image uh so most likely the only thing that's messed up is our live reload can't bind to source since it's not a known property of cached image well this is completely incorrect but what can you do the best thing you can do is actually to restart your surf command which i have somewhere in my command line uh strange i usually do it in here so let's do ionic surf again and then hope it works now in the meantime if you also want to specify more custom options um there was a package in the past that i used that a lot of options like use the image as background image or as a real image you could do all of this the only thing i wanted to show you is like having a difference um for the input spinner i will set this to false and then within our html we're going to see this in action okay do we now get the locks yeah we're gonna see the locks let's talk about this in a second and finish that first thought so you could define a lot of different things for your cached image component i just added this little spinner and once you've done this you could just do something like this if you want to show a spinner uh just show the spinner and if you don't want to show a spinner show maybe an ion skeleton text or something else so you can have a little bit of options for your cached component now as we've seen uh we get the call for set source and we're just playing this uh skeleton text right now we could now easily change this within our home page html if we want to say please use the spinner we're going to set this to true and instead of the skeleton text our component would now display a spinner that was once again really great uh maybe we should save the component and then we see we got a spinner instead so that is a way to customize your component but i actually preferred uh to have our um our little skeleton here all right we got the source now what's coming up uh from the source we need to check if we have the image already downloaded then we just need to grab the file url and display it or we need to download it and then grab the file url and display it this is basically basically the whole flow and to achieve this we're gonna start with something to grab the information from the image to now store the image uh we need two things we need the image name so we can save it somehow and we also need the file type um to create a base64 string you will see why this is necessary in a second but before we do this we gonna copy over this i have stored this so we need the plugins from capacitor core in the file system directory this is still using capacitor 2 if you're already using capacitor 3 you might have to install the file system from a different package i actually don't know if that's still in the core or a different package so maybe a little change for capacitor 3. and then we can start our journey by saying file system please read the following file and we're going to say look inside a directory and for this we're going to use our file system directory cache you could also store it in data documents whatever you want but i thought well it is caching a file so maybe the cache folder would be a good place and then we also need a path those are the two required values and this one will be our cache folder slash image name of course if your images have the same name well then you should maybe add something like random string to your the image name but for now we're going to keep it like this now this will try to read the file um there is currently as far as i know no functionality to check if a file exists usually we would first of all check if the file exists but there's no option and because that's the case we have to do this inside our catch block uh we're gonna reach the catch block if the file doesn't exist so that means we need to write the file to our file system at this point and we can easily do this but for now let's continue in the first part because here we already got a file uh we're gonna get a local file we're gonna lock this out once we're able to get this but of course first we need to load it so set to source at this point to write the file uh we now need to implement a little logic um i found this inside the capacitor no inside the ionic forum actually inside the community and i will put in the link as well i think matt uh posted this well let's check it quickly out if it was mad uh so who gets credits for this function yeah the good old net cow um we're gonna store an image from the url because if we look at the api response that we get and that you usually get from your api uh you're gonna have for the image uh something like this if you already get a base 64 string or a blob uh saving might be different but let's say you from your your from your api also get back a string like this that means you need to download the file from that place first of all and that's what our store image functionality does uh we can easily use the fetch api you could also do this with the angular http client for the fetch api i had to add my little proxy in front of the url because for the images there was actually no course implemented and then we get into problems so maybe you're gonna have to use a proxy for your own as well once you get the response you can convert it to a blob and once you've converted it to a blob you need one more step which was also mentioned by net by med is convert blob to base 64. the reason is simply if you want to write the file to the capacitor file system you need to pass in a string for the data and therefore we just need to add the base64 data here we're going to use the cache folder once again and the path will be very likely our image name and the directory should be the same you use in all the other places so make sure you're really using that all over the place and this just converts our function using the file reader from blob to base64 okay with the store image in place we can heat over back here once again back to our lock where we want to write the file so let's await our function this dot store image uh the url to the image should be our image url that's where we want to download the image from and then we got the image name in the second place okay now we have stored the file and that means we can now read it because the write function actually doesn't only returns a file yuri that's not really helpful uh at this point we can now once again read the file from the cache directory same path like before and then we're most likely in callback hell with a lot of then in here no it's a it's fine i think it's okay you could maybe do this with observables somehow as well but it will work like this trust me and at this point we're at the same place like we are here and now the only thing we need to do is set our source and we can do this by just saying data image whatever our file type was base64 and the data that we've written from the file and same goes into the then block here it's just one additional step to store the image which performs a lot of interesting things in the background and then we can store it okay uh we got this in place um there was a little problem for um using this code on a device and that was that the parent folder didn't exist so our cool cache folder didn't exist initially if you had a service i would recommend to put in some kind of init logic like we had in the previous tutorial about api caching for now what we're going to do is we will just heat over to our app component inject this and then create a function like this to create our cache folder right in the beginning so this will make a directory at our place using cached img and then we got this set up in the beginning now if we save everything and heat back to our application we now should see something interesting okay we got a look for set source um and as we can see suddenly they are images once again now how did this magic work if you go to the application and then we add some locks i'm a bit confused i always i got a local file yeah i didn't set a lock here because we reached the catch block we stored the image we read it and then set it to our source but we can verify this by going to application file storage and if it looks empty don't panic just click refresh and we see we got the folder up here which was created and then we got all the files content whatever whatever interesting information and what happens next is that if we now press load products they will basically be immediately here we get set source and we see local file with the base64 data in here and how did the spinner get there i really don't know where where is this spinner interesting um we can now check also our network tab and let's clear this and let's load the products and we see no calls are happening anymore well to really verify this in the end you could also easily create a function to a clear cache which we also had in the past tutorials i will just quickly add this to our homepage only for testing uh this will get the directory for our cached images once again having a const and exporting it somewhere might be a better idea than to just have this string all over the place in your application uh and then it will iterate all the files and for each of the files call delete file to call that let's add a quick button to our home page up here to clear the cache and maybe we're going to set also our products to an empty area afterwards and once we got that let's finally check it out so we're loading the data and we already see everything's coming from the memory cache uh if i do it again same behavior now let's clear all of this and let's load it again and we're doing all the funny requests again i don't know why you say memory cache because uh not sure about that shouldn't be the case let me quickly check you didn't remove everything my friend clear cache clear cache why didn't you remove my files delete or i i guess we already downloaded them once again right um said source network tab uh maybe they they don't appear there because we are downloading them now if i do it again it should definitely look different yeah we're just making a call to products as we can see and all of our files are now once again inside the file storage so we can manage this you could also add more information to a different place like the time to live for fire are for file images but right now we could now easily throttle our network to something like slow then load the product of course the call to the api in general will be slow but those four kilobytes will still be fine enough and we immediately got all the images remember in the beginning when we didn't have the images or if we close this and now do it again downloading all those images is really painful for users with a slow collection uh connection it takes about like 10 20 seconds really depends uh on the connection um but we also got that covered with our skeleton in the background which is replaced once we've downloaded the file and once we can read the file from our file system and now we got everything i think we got everything and we could clear this again load the products we're still slow but now we're only loading products and immediately got the list so that's our image caching with a super simple component that i hope you can integrate quickly into your own applications all right and that's it for today that was the second part i hope you know understand basically everything about how you can implement your own caching mechanism from caching json strings inside ionic storage to caching image files using the file system uh we haven't seen this approach on a device but trust me i've tried it um the only thing that we had to do was create this parent folder for the image cache component for the image cached files upfront but that was basically the only custom change that i had to do in this code to make it work on a real device give it a try combine it with the previous tutorial use the service to export the cons so you don't have them all over the place in your applications and then i really hope that those two components and tutorials help you to implement your own simple caching which actually isn't too hard to do in your application so your users benefit from local available data once again if you're not in a member go check it out ionicacademy.com my place to help you with everything ionic if you enjoyed the video of course also give it a like and hit the subscribe button so you get notified about all the upcoming videos about ionic and the other topics there well mostly ionic anyway have a great week and enjoy the code and happy coding [Music] simon you
Info
Channel: Simon Grimm
Views: 4,031
Rating: undefined out of 5
Keywords: ionic framework, learn ionic, angular, ionic angular, ionic guide, cross platform, hybrid app, ionic for beginners, ionic course, ionic, cordova, javascript, ionic 5, learn ionic 5, ionic 5 for beginners, angular 9, ionic 5 tutorial, ionic 5 angular, ionic 5 course, ionic academy, ionic tutorial, ionic cache api, ionic image cache, ionic image caching
Id: l7hsRrjLGUY
Channel Id: undefined
Length: 23min 10sec (1390 seconds)
Published: Tue Jun 08 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.