IONIC Framework Web and Mobile Technologies | My Assignment Tutor

15/12/20201IONIC Framework Web and Mobile TechnologiesLecture 81ObjectivesIO N IC DYN AM ICCO M PO N EN TSH AN D LERS AN DCALLBACKSAD D IN G PLATFO RM SAD D IN G PLU G IN S BU ILD IN G /D EPLOYIN GYO U R APPS2DynamicComponents315/12/20202DynamicComponentsThese are the components that havedynamic interactive functionalityThere are 8 of these present in ionicframework, but you can create customcomponents to add more functionalityWe will try to go through some examples inthis lecture, and see how to work with them4DynamicComponentsContd.N ow let’s look at anexam ple of the AlertCom ponent and thedocum entation for it:You have already usedsom e JavaScript alerts inyour subm issions for theCALet’s say w e w ant an alertto popup w hen the userclicks the dem o button5DynamicComponentsContd.– First, we need to add the controllerto our HTMLDemo Button615/12/20203Dynamic Components Contd.– Then we need to import the controller associated with theAlert Component– So let’s add this import to our home.ts fileimport { NavController, AlertController } from‘@ionic/angular’;7Dynamic Components Contd.– Once we have imported the controllers, we usedependency injection to inject this to the constructor– We do this, so that we can use it later. To do this weupdate our constructor declaration as shown below:constructor(public navCtrl: NavController, private alertCtrl:AlertController) {}8DynamicComponentsContd.Finally let’s createthe openAlert()methodasync openAlert(){let alert = await this.alertCtrl.create({header: “Demo Alert”,subHeader: “Demo subtitle”,buttons: [{text: “YES”}, {text: “NO”}]});alert.present();}915/12/20204DynamicComponentsContd.– The result of clicking on thefirst demo button, or anydemo button you added theclick method to will be an alertbox, tailored to the platformyou’re using10AddingHandlers andCallbacks11Handlers andCallbacksHandlers and callbacks allow you to make theapp more useful by letting you decide whathappens when a user clicks on somethingHandlers are mostly used when you want toperform an action when a user clicks onsomethingCallbacks are the methods that you send to thefunction, and they will be called when the calledfunction has finished its functionality1215/12/20205HandlersContd.As mentioned earlier, handlersallow you to make the app moreusefulThey will be called when a userhas performed a specific actionon the app, or on one of thecomponents within the appSometimes it might be worthsending a reference of the eventor the target to the handler toperform the action appropriateto the event13HandlersContd.Let’s add some handlers to the AlertComponent that we added to our demoearlierWe have two buttons, ‘YES’ and ‘NO’ in ouralert component, and we will add a handlerfor each of themFor the purposes of this lecture, we’re onlygoing to use the console and log the eventthere14HandlersContd.– We will update our app tohave the handlers for eachof the actions and clickingon either of the buttonsshould call the respectivehandler– The result of this can beseenin the consoleasync openAlert(){let alert = await this.alertCtrl.create({title: “Demo Alert”,subTitle: “Demo subtitle”,buttons: [{text: “YES”,handler: () => {console.log(‘YES clicked’);}}, {text: “NO”,handler: () => {console.log(‘NO clicked’);}}]});alert.present();}1515/12/20206HandlersContd.– We can also getthe event passedonto the handler– Ionic willautomatically passthe event variableto the handler– The event willinclude informationabout the eventand the target,which can be usedto make thehandler even moreusefulasync openAlert(){let alert = await this.alertCtrl.create({title: “Demo Alert”,subTitle: “Demo subtitle”,buttons: [{text: “YES”,handler: () => {console.log(‘YES clicked’);console.log(event);}}, {text: “NO”,handler: () => {console.log(‘NO clicked’);}}]});alert.present();}16AddingPlatforms toApp17AddingPlatform tothe App– You will need to add theplatforms for the app, beforeyou can build and exportyour project for the relevantplatform– You will also need therelevant SDKs installed onyour computer in order to dothis– We will look at adding theAndroid platform to thedemo app1815/12/20207AddingPlatform tothe AppContd.For the android platformto work, you will need toinstall the Android Studio,Android SDK and JAVAFor iOS, you will need theXCode installed on yourcomputerTo add the androidplatform, run thefollowing after installingthe pre-requisitesionic cordova platformadd android19Adding Platform to the App Contd.Complete details for the Platform Addition available on:– iOS:– Android: toApp2115/12/20208AddingPlugins to theAppWe have a number of plugins available for theionic app to choose fromAs a part of your CA, you’ll need to add someplugins to your appWe will look at how to include plugins, these arejust a few examples. Choose the plugins toinclude appropriate to your individual scenarios22GeoLocation/GeoFencePluginWe need to install/addeach plugin to our appbefore we can start usingitLet’s add the GeoLocationand GeoFence plugins toour app for the tutorialGeoLocation will allow usto fetch phone’s currentpositionGeoFence will allow us todefine a radius around theGPS coordinates23GeoLocation/GeoFencePlugin Contd.To add the plugins to the app, we are going to run thefollowing commands on our terminalionic cordova plugin add cordova-plugingeofencenpm install –save @ionic-native/geofenceionic cordova plugin add cordova-plugingeolocationnpm install –save @ionicnative/geolocationNote: You have to do this in your project directory2415/12/20209GeoLocation/GeoFencePlugin Contd.After adding the plugins, you will need to import theplugins to the appropriate page of your appLet’s say we want to do that on our notificationspage, that we added last weekimport { Geofence } from ‘@ionicnative/geofence’;import { Geolocation } from ‘@ionicnative/geolocation’;25Adding someproperties tothe page– We will add a few properties to our notificationspage nextradius: number = 100;error: any;success:any;– radius: is the radius we want for the geofence– error: will be used to detect errors– success: will be used to determine completion of theaction26Updating the ConstructorWe will need to update the constructor and add the dependency injectionsconstructor(public navCtrl: NavController, private platform: Platform, private geofence:Geofence) {this.platform.ready().then(() => {geofence.initialize().then(() => console.log(‘Geofence Plugin Ready’),(err) => console.log(err));});}2715/12/202010Adding theMethodssetGeofence(value: number) {this.geolocation.getCurrentPosition({enableHighAccuracy: true}).then((resp) => {let fence = {id: “myGeofenceID1”,latitude: resp.coords.longitude,longitude: resp.coords.latitude,radius: radius,transitionType: 2}this.geofence.addOrUpdate(fence).then(() => this.success = true,(err) => this.error = “Failed to add or update the fence.”);this.geofence.onTransitionReceived().subscribe(resp => {console.log(resp);});}).catch((error) => {this.error = error;});}28Understanding the Method– setGeofence is a method we will call when we press a button, thiswill also receive the radius as a parameter– We use geolocation.getCurrentPosition() to get the phone’scurrent position– enableHighAccuracy will ensure we get a high quality position– If the call is successful, we set the handlers for various events29Understanding the Method– geofence.addOrUpdate() is used to create or to update anexisting fence– geofence.onTransitionReceived() is called when the saidtransition is received– This can be 1 (Entering the Geofence)– 2 (Leaving)– 3 (Both)– We have used 2 as a transition type in our case3015/12/202011Updating theModule.ts– You might start getting the error that you have no providers forGoelocation and Geofence– Update you app.module.ts file and add the providers forGeolocation and Geofenceproviders: [StatusBar,SplashScreen,Geolocation,Geofence,{provide: ErrorHandler, useClass:IonicErrorHandler}]31Verifying theAPIconfiguration– In order to verify the api configuration, you’ll need to run thisapp on a mobile device– As you might have noticed, we already added the platformetc. to our app– To run the app on a device run the following command (this isfor android)ionic cordova run android –device32App Result– When you run you app forthe first time, the app willrequest the locationpermission3315/12/202012AddingPlugins to theApp Contd.– When you start your ionic project, it adds two plugins bydefault– These plugins are:– SplashScreen– StatusBar– You’ll however need to update your splash screen to suit yourapplication– Note: You’ll need to deploy the app to a device or an emulatorto see the SplashScreens34Deployingthe App on aPhone35Deployingyour apps– Some of the tools and utilities that you need to test for theapp might not be available for the browsers– To test these, you’ll need to deploy your app on a mobiledevice or an emulator– Let’s see how we deploy an app on a mobile device3615/12/202013Deployingyour appsContd.– To deploy the app, you’ll need to prepare the environment forthe deployment– You will have to setup the necessary kits and SDKs for eachplatform in order to deploy your application to a mobile device– The environments are different for each platform, and theconfiguration depends on the host machine you’re using towrite your app37Deployingyour appsContd.– A detailed set of instructions is available online to enable youto setup the environment for deployment of the apps– I have included the links on the next slide for you to be able toconfigure the environments accordingly38AddingPlatform tothe AppContd.Complete details for the Platform Addition available on:– iOS:– Android: theapp forAndroid– Once you have configured the platform and environment forthe desired platform, you can deploy your app in either debugor production mode– We have already seen how you deploy the app to an androiddevice– The debug mode is chosen as a default mode of deploymentwhen you deploy an app to a device40Deploying theapp forAndroid– If you don’t want to deploy the app, but only build the app fora desired platform, you can do so by runningionic cordova build android– The resulting apk can be found inplatforms/android/app/build/outputs/apk/41What’s in nextlecture?– Gestures– Preparing a Production Build for your Apps– CodeSigning the production builds4215/12/202015Questions?43CA 2CA2 PUBLISHED CA2 DEADLINE 21/04/202011:59PM44


Leave a Reply

Your email address will not be published.