Going Mobile: Wrapping an existing web application in Cordova/Phonegap

Going Mobile: Wrapping an existing web application in Cordova/Phonegap

There are many choices to build mobile applications, from native to the growing popularity of hybrid development, with everything in between. In all of these cases, as a developer you would be writing a brand new mobile application from scratch with the ultimate goal of deploying to one the app stores. Let’s say that a company has an existing web application and for reasons we will not debate here, management has decided that this web application is to be packaged and delivered as a mobile app available from the main app stores. How would you go about it from a development perspective and what would be some of the pitfalls and difficulties to take into account when engaged in this endeavor? This article will attempt to cover these and offer some solutions based on actual experience.

Design

The first and most crucial problem that you will have to resolve before doing anything is ensuring that:

  • Your web app is responsive
  • Your web app uses mobile friendly form controls

The second point is actually quite important if you’re using custom controls that will not be rendered natively by the mobile browser (I am looking at you Bootstrap dropdowns). You will have to scour your application on a mobile screen to ensure that the experience is consistent and frustration free for your target users. I emphasized target here because if your goal is to keep your application available through the web but still be available as a mobile application, I can almost guarantee that you will run into design issues where one platform will have to be favored over the other for optimal design so be prepared to make these choices when they come up.

Assuming that your design is now mobile ready. How do you go about wrapping into something that will feel native to your users?

Phonegap/Cordova and the InAppBrowser

Adobe PhoneGap is a distribution of Apache Cordova and Cordova is an open-source mobile development framework that allows you to use standard web technologies — HTML5, CSS3, and JavaScript for cross-platform mobile development. In simple words use standard web development tools to create and deploy mobile applications from a single codebase across different platforms. Phonegap offers some additional enterprise services for the development and deployment of your Cordova application but in essence you will always be working with Cordova under the hood.

What’s interesting about Cordova is that it can be extended using plugins which allow your app to use native device capabilities beyond what is available to pure web apps. That is how your standard HTML, CSS and Javascript codebase can hook into the phone’s camera or microphone to perform native functions, reinforcing the illusion of native to your app’s user. One of these plugins that can be made use of to wrap an existing application into a native app is the InAppBrowser who started as an independently developed plugin before being incorporated as a core Cordova plugin. It’s basically a child web browser that allows you to access third party web content. Wrapping an existing web application as a native application comes down at this point to loading said web application in an InAppBrowser window and managing the whole mobile app experience.

In practice, the loading is the easy part, with the managing of the mobile experience come the hard parts.

Cross Window Communication

Outside of just authentication, there will be many instances where you will find yourself wanting to communicate values between the wrapper app and the wrapped app in the inAppBrowser window. This great article by TJ VanToll lays the foundation for how to to just that even though it dates from 2013. Basically by making use of the inAppBrowser executeScript function, and using localStorage, you can exchange values between both windows. It’s not a standard way of operating but while waiting for Cordova to implement the window.postMessage specification in the InAppBrowser, this remains the most effective way of going about cross window communication.

Authentication and Session Management

If your application only consist off content that does not require authentication, you’re home free. Skip the rest of the article and enjoy yourself a cold drink. For the majority of cases the existing application is without a doubt functional only after authentication. With authentication also comes session management not only in the context of your application but also in the context of your user being on a mobile phone with the expected corresponding behavior. The following questions need to be answered

  • How long does the session last once the user is authenticated? In web applications, users are used to re-authenticating every time their session expire but on mobile, the expectation is to authenticate once and forget it, or use other less intrusive mechanisms like fingerprint reading or pin entering when security must be enforced. The takeaway is that you should not make the user have to enter a username and password every time they open the app if they really don’t have to.
  • Is your Forgot Password application flow mobile friendly? Does it require users to perform steps (Captcha) that are easy to do on a computer but would be more challenging on a mobile device? If not, you will have to adjust your flow to use more mobile friendly techniques (verification codes sent by SMS or Email).
  • What happens to your application when the user navigates away from it? Do not assume that your application will always be front and center, what happens when a call comes in and last longer than your session duration? What happens if the user sends the application to the background and then comes back to it a couple of days later? How would you know the state of the application at that time?

These questions show that even though the goal is to simply wrap an application in an hybrid app, to ensure an optimal mobile experience you will sometimes have to write additional code in the hybrid app to handle these different situations. For authentication and session management, the general idea is for also the hybrid wrapper to be aware of the authenticated and session state of your application.

Cookie Authentication

If your application uses cookies for authentication and session management and you don’t need to add an extra layer of security or convenience like fingerprint authentication, you will need to make sure that when opening the InAppBrowser window, you set the proper option for the window to remember cookies, otherwise if you kill the app and re-open it, your session cookies will be gone and the user will need to re-authenticate:

var ref = (url, target, options);

From the documentation:

options: Options for the InAppBrowser. Optional, defaulting to: location=yes. (String)

The options string must not contain any blank space, and each feature’s name/value pairs must be separated by a comma. Feature names are case insensitive. All platforms support the value below:

location: Set to yes or no to turn the InAppBrowser‘s location bar on or off.

clearcache: set to yes to have the browser’s cookie cache cleared before the new window is opened

clearsessioncache: set to yes to have the session cookie cache cleared before the new window is opened

The clearcache and clearsessioncache options are available on both Android and iOS and for clearsessioncache it should be set to no to ensure that your session cookies are remembered.

Token Authentication

If you’re using a token based authentication strategy and want to add fingerprint or pin-based authentication, you will need add extra code to the hybrid app to check for the state of the user when the app opens and present them with either a login screen or a fingerprint/pin reader. Refer to the Cross Window Communication section on how to communicate this state between the wrapper and wrapped apps.

External Links

A (nasty) little gotcha from using the inAppBrowser is that clicking on a link to external content, while you are in a inAppBrowser window will load that content in the inAppBrowser window you are using which leads to the following scenario:

  • User is enjoying your app thinking it’s native as your design job is excellent.
  • User sees a link to let’s say a Twitter page and “clicks” on it
  • The Twitter page loads in the InAppBrowser window, replacing your app with the Twitter page where your app screen used to be.
  • Extreme confusion ensues as the task manager shows that the user is indeed using your app, but they have no way to get back to your app content on iOS, or have to use the Back button on Android, and at this point the magic of native feel is broken.

The expected behavior would have been for the link click to open in a new OS Browser window, keeping the application intact and allowing the user to get back to it once they are done.

The solution in general is to track every external link with a script and open them using the window.open(url, '_system') call as illustrated here. Remember that this script will have to run in your wrapped app to work otherwise you will need to communicate the link url back to the wrapper app and issue the window.open call.

Android Only: Back Button

On Android you will have to be careful and plan out what happens when the user clicks on the Back button whether it’s a hardware or software button. If your wrapped app is a SPA, this can leads to some weird situations with your app state.

First thing to know is that there is a configuration for it in the InAppBrowser launch options:

hardwareback: set to yes to use the hardware back button to navigate backwards through the InAppBrowser‘s history. If there is no previous page, the InAppBrowser will close. The default value is yes, so you must set it to no if you want the back button to simply close the InAppBrowser.

If it is set to yesand your SPA handles back history fine, if the user gets back to the first page in your history and touches the Back button again, they will be taken back to the entry page of your wrapper app! Again not optimal and it breaks the experience of native and leaves the user confused again. One way to handle it would be to listen to the exit event on the InAppBrowser window so that when it is closed, the wrapper itself also is closed. Check this StackOverflow issue for alternatives.

Angular Only: ngZone for event handlers

After working with Cordova/Phonegap for a while and installing plugins, you’ll become familiar with how Cordova exposes functionality through events and event callbacks or promises. One gotcha if you’re working with Angular (>v4) is that these are events that are happening outside of Angular and if you remember even from AngularJS, any event happening outside of AngularJS needs to be synced with the AngularJS digest cycle using the $scope.apply() function. It’s no different in Angular expect now that Angular run in zones and uses the ngZone.run() function to re-enter the Angular zone. If you have Cordova plugin events firing and you are not able to tap into them in Angular, make sure to capture the event within a run function call as illustrated here in this example service for the Back button event being fired.

import { Injectable, NgZone } from '@angular/core';
@Injectable()
export class BackButtonService {
constructor(private logger: DebugLogService,
private ngZone: NgZone) {
document.addEventListener('backbutton', () => {
this.ngZone.run(() => {
console.log('Back button has been pressed')
});
}, false);
}
}

Summary

Although the initial goal of wrapping an existing web app into a native mobile app might look simple enough with Cordova/Phonegap, in practice there a quite a few pitfalls in making sure that the experience is optimal for users and fulfills their expectations for what a native app experience is. Behind the scene there will be quite a few orchestrations to put in place to maintain the illusion of native. I would then only recommend this approach as a stop gap measure while either a more appropriate native or hybrid app is being developed. Even they don’t work on Safari yet thus making them a more limited choice at this point, Progressive Web Applications are also a very viable option when targeting mobile applications.

Advertisements

Understanding the developer ecosystem in West Africa Part II

Disclaimer: This is an opinion based on my experience, observations and interactions in the developer ecosystem in West Africa, more specifically Senegal and Cote d’Ivoire.

In my previous post I talked in general terms about some of the issues affecting the developer ecosystem in West Africa with a promise to dwell more into the details in a subsequent post, so here we are. My initial post briefly touched on the skills gap issue and in this post I will try and focus on the reasons why. To make the writing of this post easier, i will repost the problem statement of my previous

You will hear complaints from local developers that they are not valued enough by local companies with major projects (enterprise) being sent out to Northern Africa (Tunisia or Morocco) or France to be coded at a premium therefore robbing local companies of much needed revenue and developers of much needed opportunities to build and scale major projects. On the flip side, you will hear horror stories from companies that tried local talent and ended being burned bad with awkward solutions that were badly implemented if implemented at all and are a maintenance nightmare making them resolute in exporting the coding work on the next implementation to make sure they end up with a quality product.

How did we get there?

1) Education

This problem is not unique to Africa in general but finding tech talent with employable skills right out of college is difficult. The accepted wisdom amongst the CEOs and managers I talked to was to expect an initial training period after hiring to get to a certain level of productivity out of new hires. From developer themselves, they expressed a certain level of frustration with the quality of the education made available to them in the field of computer science. Complaints covered the sometimes questionable skill level of the instructors to the inability to sometimes being able to practice the craft they are learning due to lack of proper infrastructure. On that end, it’s not unheard of in certain private or public schools to follow a “programming” cursus without ever compiling or writing a single line of code on a computer all the way to graduation. Now as I said earlier, I’ve interviewed my share of college students for internships here in the US that I deemed not qualified because outside of college courses they didn’t have much to offer in terms of usable skills. The ones hired were the ones that went beyond school work and had side projects that showed self-starter spirit, and the ability to learn independently that are actually crucial for a successful developer career. These qualities are universal in my opinion and will apply not matter the context but even in the US, I feel there should be a tighter cooperation between the business community and the Computer Science academia in order to produce the types of graduates that will be day one contributors to businesses (and that means graduates starting businesses as well).

2) Language

This more specifically applies to French speaking West Africa with all coding languages being native English constructs, and most material, tutorials, answers and questions being produced in English, French speaking African developers find themselves at a disadvantage when the only way to get past a nasty bug or implement a new feature based on solid architectural research requires Google Fu skills most natural to English speakers. The good news is that most develop a reading and writing proficiency that helps in most cases but the lack of fluency is definitely an obstacle to better and/or quicker code fluency. This is why at Coders4Africa we insist on being an English only company for conducting every day business as it will only help our French speaking developers being more proficient at their craft.

3) Cultural and Social Context

To each country their own culture and social contextes and in projects that span multiple countries, interactions between team members with different expectations can lead to awkward situations with different level of seriousness to them. For these developers working locally for international clients in the US or Europe, most problems I’ve encountered were focused on communication and that’s understandable. I’ve been part of a distributed team and one of the most successful success factors for this type of team is a high level of intra team communication to make up for the lack of physical proximity. The same concept applies for a client getting their project done remotely, a high level of communication ensures a high level of confidence for the client. The complaints that I have heard from clients the most was that developers would often disappear for long period of times, being unresponsive to emails, and when they presented work it was not up to the client’s requirements. Big surprise. Of course a whole lot can go in there in terms of project management and using some kind of agile project management methodology but if neither the client nor the developer are familiar with it, it makes for a tough interaction.

In terms of work habits as well, and this is more geared towards customers in the US, American are known work horses and expect the same out of their counterparts. Mixing those expectations with the more laid back approach to deadlines and work delivery of certain shops can lead to let’s say unpleasant situations. It’s just not Americans, for expats coming back from Europe or the US and launching startups, this turns out to be one of the most difficult aspects of working locally. Things just happen slower. Of course if the work is geared towards international clients then there is no way you would be able to sustain a business and this requires coaching and training staff to meet these international standards.

4) Exposure

I hesitated a lot to use the term exposure as one of the issues but allow me to use for lack of a better terms in my mind at the time. Throughout the multiple conferences we held for Coders4Africa, the most popular event we held were the developer workshops we held to expose local developers to the different frameworks and tools we used to do our work. This is where the most productive exchanges happened and where I enjoyed the most. Being a front end developer, being able to talk about AngularJS, TDD, build tools, continuous integration, APIs, and seeing the light go on was and is extremely gratifying but when I mentioned exposure, it’s to get back to the point that I know about these concepts and tools for the most part because:

  1. They’re common usage where I worked
  2. I’ve learned about them in school before
  3. I keep myself updated on what’s going on in my industry

To link back to my previous point about education, if the foundation is not solid, it will be difficult for the house to stand strong. Sometimes it’s just a matter of being exposed to the right kind of information. Sure some will tell me that it’s the individual’s responsibility to seek knowledge and get better, which is true to a certain extent, but the ease in doing so is not evenly distributed in the software world. I will expand more on that in my next point

 

5) Thriving business to development ecosystem

I have been fortunate to spend my career here in the US where a lot of the innovation in software development not only takes place but is then actively used by businesses/startups when it is not actually created by businesses/startups. This dynamic environment indirectly ensures that the workforce in general is always up on the latest trends in the industry if not actively at least passively. Programming for the most part in the US is a lucrative occupation, with demand outpacing supply. Businesses have recognized the importance of technology to their bottom line and invest in and compensate their developers properly to attract the best and ensure retention. I feel that is quite not the case yet in West Africa although awareness is increasing. The industry though as a whole needs a serious injection of capital to foster the kind of sustained innovation we see in the US and Europe.

 

The silver lining

Now that I am done painting this apocalyptic picture of this ecosystem,  I would like to end by reminding you that this post is specifically focused on the problematic aspects of the ecosystem. Ask somebody to write a piece about the state of the developer ecosystem in the US and you would get something as grim, certain problems are just universal.  In spite of these problems, what you should remember is the amazing number of skilled developers that defies these odds to bang out crazy good code, launch and support startups. Those are the real heroes in my opinion. I just wanted to talk about these to surface past conversations that I believe are still happening today in order to improve the eco system as a whole. I am a firm believer when it comes to African tech that a rising tide lifts all boats and a thriving African tech ecosystem with international recognition will be a boon for us all. In any case, I hope this starts a conversation where we can all learn from and come up with actionable items to help fix these issues, which is the real goal of these posts.

 

 

 

Understanding the developer ecosystem in West Africa Part I

Disclaimer: I don’t pretend to give scientific result based on accurate polling or any kind of scientific method (outside of observation). This is just a summary of my observations so treat it as what it is meant to, an opinion based on my interactions and experience. Furthermore as my experience extends to Senegal and Cote d’Ivoire so I’d scope my remarks to these two countries even though the title says West Africa.

I was fortunate to have the opportunity to work remotely this summer in both Dakar and Abidjan and it was great to be able to experience my daily developer routine within the slower pace and context of these cities. I was also able to network with local developers and the companies that hire them and get feedback from both parties. It was mind opening and I’ve walked away with a new insight and passion for bettering certain aspects of the current situation I will dwell on shortly.

The Good

Well, I’ll start with the easiest: being home.

On top of my family, being able to see my aging parents on a daily basis was invaluable. Being able to trod the same roads and alleys I’ve been on as a teenager with a new set of eyes and different experiences was great. Seeing old faces, catching up on common acquaintances, shortly, the whole experience of being back after a long time away is good. it’s like finding an old part of yourself that you thought was gone for good.

Getting past the nostalgic personal part, what was really good about banging out code locally?

  • Internet connection: I opened an Orange 4G mobile prepaid account as most people do, and to resume my experience in Dakar, i never felt like I was lacking and that the connection was unusable. That experience also extended to the home DSL connection where i was able to Netflix to my leisure without a noticeable drop in quality. So pushing to Github was definitely not an issue. It was not all rosy though but I’ll expand on that as part of the Bad.
  • Co-Working Spaces: Outside of the Coders4Africa offices, I worked most of the time from Jokkolabs and I enjoyed the space and the professionalism of the staff. Whether it was the Internet connection or finding a private room for calls, everything was handled with the professionalism of a well run operation. Outside of local startup working out the space, I could pick out expats and other nomads working out of the space just like me.
  • The Developer Ecosystem: The constant with the majority of the developers I met was how much more they wanted to know how to get better, asking for tips and feedback. There are actors making things happen in order to elevate the skill level (Noting Leger Djiba and his A2DG initiative ) with meetups and coding events being pretty frequent.

The Bad

For every head there needs to be a tail so I also have to talk about the negatives I either experienced or were brought up during discussions with local actors.

  • Bandwidth: As mentioned earlier, bandwidth was pretty good in Dakar but Abidjan was a different story with a slower bandwidth in general, and areas where I would just lose the connection. This was with an Orange SIM card as well. When it worked it was decent, and I was able to get my work done properly. Your mileage might vary depending on the country.
  • Internet cost: If I am not mistaken decent Internet Access was declared a human right but operators are still treating it as a privilege. The prepaid model is the de-facto operation mode for Internet access in most West African countries but it can run pretty expensive. If i remember correctly, 24 hours of 4G access (2GB max) was billed at about 2 dollars in Dakar, which can run expensive if you don’t pay attention. Home plans for 10MB of ADSL Unlimited Data will run you about $65 a month.
  • Skills Gap: I mentioned earlier that there is a young and eager local workforce and what surfaced through my interactions, and I am talking here from my background and experience as a front end developer, for the most part, they are developing with “antiquated” toolsets , frameworks and processes. I want to clarify that this is not a case of me being a “let’s play with the latest industry toy” fanboy but when you have developers sharing code using email instead of a repository, you know you have a serious problem. This whole discussion in itself deserves an article of its own to get into the other symptoms, causes and  solutions  but there is an undeniable skills gap in general when it comes to software development as it is done by the best. This is one of the reasons why we originally started Coders4Africa in 2009, to create a pan-african community of developers while at the same time providing the training needed to eliminate that skills gap. This has evolved into Gebeya, launched last month in Ethiopia and first in what we hope will be a network of professional training institutions focused on producing polished and skilled techies for the local markets.

The Ugly

Seriously, there is nothing I would qualify as ugly so I would just use this section to summarize an issue that was brought up quite often, both in Dakar and Abidjan, in an attempt to start a discussion. It goes like this:

You will hear complaints from local developers that they are not valued enough by local companies with major projects (enterprise) being sent out to Northern Africa (Tunisia or Morocco) or France to be coded at a premium therefore robbing local companies of much needed revenue and developers of much needed opportunities to build and scale major projects. On the flip side, you will hear horror stories from companies that tried local talent and ended being burned bad with awkward solutions that were badly implemented if implemented at all and are a maintenance nightmare making them resolute in exporting the coding work on the next implementation to make sure they end up with a quality product.

Now before going any further I am not implying that ALL local developers suck, or/and that ALL companies have had bad experiences using local talent to get software built. Based on my limited set of interactions this was a recurring comment which makes me think that the issue is widespread enough to be noticeable by all parties. As i mentioned earlier, this deserves an article of its own that I will hopefully get to later, there are many moving parts to it and I want to give it justice. As they say, where others see problems an entrepreneur sees opportunities and I am working with others to bring a credible solution

I would summarize this first post by saying that it was an eye opening experience for me and I hope to be soon one of the forces with Gebeya, Coders4Africa and others I can’t yet talk about that are working locally (and internationally) to improve the ecosystem so that African software development becomes a force to reckon with.