How to build your own Phonegap clone on iOS

This is a mini guide on how you can build a iOS wrapper to run your web app.

This is an excerpt from my upcoming Clear Hybrid Apps ebook. Visit the site, subscribe to the newsletter and I’ll let you know when it’s ready or when another post this is published here.

Why not use Phonegap, you ask? Yes, it is a great tool but perhaps you you want something simpler or learn how to do it from scratch.

First you need to install Xcode from the App store on your Mac. You really need a Mac or a VM with Mac OS X.

If you don’t know how to program in Objective C don’t worry, you will learn a little as you follow this guide.

Open Xcode and start a new project. Choose the “Empty Application” template.

1

Enter the project name, your information and the device type. For this example I picked just an iPhone app. Next, choose a location where to save the project and click “Create”.

2

We’re now presented with the default view for the project. You can see the file tree on the left, the utilities on the right column and the file being edited in the main centre area. Don’t worry you don’t yet understand everything in this window, you will learn bit by bit.

3

Let’s see what the app is up to. Click on the play button on the top left (or just press CMD-R).

The project builds and after a couple of seconds the iOS Simulator opens and you’re presented with your app. As we picked earlier the empty app template, there is not much to see, just a empty screen, but it is our app empty screen.

4

Let’s create something to put in there. First, quit the app on the Simulator (press the Stop button in the Xcode window). On the left column click on the “AppDelegate.m” file. This should open the file in the main editor.

5

There is a lot of boilerplate stuff here. This file is the main entry point to an iOS app and we’re going to create here a controller to manage the navigation for us, like any other iOS app.

Locate the application:didFinishLaunchingWithOptions: method. Should be on a line like this:

This method is called by iOS when the application finishes launching (hence the name), and as you can see the default action is to create a single window of the same size as the screen and set its backgound colour to white.

Place your cursor on the comment that says “Override point…”, and paste this block. You can enter some new lines to make it clearer.

6

Press run again and the app will be a little different: we now have a navigation bar. Empty, but it’s there to use!

7

We’re now going to create a View Controller to serve as a container for our web view. From the Xcode menu, pick “File” > “New” > “File” (or press CMD-N), choose a Objective C class from the iOS / Cocoa Touch folder.

8

Call the file WebViewController and make it a subclass of a UIViewController. We will be doing everything in code, so don’t pick the checkbox to create the XIB as well. Click on Next, add it to the project by clicking on the Create button. You can costumize a lot of the project but the defaults are usually good enough.

9

There will be two new files in the project WebViewController.h and WebViewController.m with some boilerplate in there. You can remove some of it later, but let’s leave everything as it is for now.

First thing, let’s integrate this into the AppDelegate code we did earlier. Open the AppDelegate.m file again and on the top of the file include the WebViewController.h file. Type the following on a new line after the other include that is in there

This will include the WebViewController declaration in this file so it can be found. On the application:didFinishLaunchingWithOptions method, before the (…) initWithRootViewController:nil (…) file, type the following line:

and replace “nil” with the “wbc” variable in the next line, so you end up with this:

10

(you can see I hid the right column and the debug console to maximise the editor area, you can toggle them with the buttons on the top right of the Xcode window).

You can run the app again. It should compile and launch without any issues but you won’t see anything different.

We’re going to need add two things to the WebViewController public declaration: a string to set the address the view should load, and the web view itself. Open the WebViewController.h file and type the following between the @interface and @end lines.

This declares the two properties. Xcode handles the details for us.

11

Open the corresponding .m file and inside the initWithNibName:bundle method, on the same spot as the comment that says “Custom initialization”, enter the following:

12

Run the app again, and while it doesn’t seem too different, you can now drag the screen up and down, as you’re now acting on the web view. It is empty because we haven’t yet told it what to load.

13

To specify what address to load we’re going to set corresponding property when we initialise the WebViewController object in the app delegate. Open the file and type the following:

14
We need to instruct the webview to load this address when the view is loaded. Open WebViewController.m and after the viewDidLoad method, after the comment, add this new method:

15

Press Run and the BBC homepage should load in your app!

16

There is still a lot to do. There is not way to go back, the pages load in the same web view, there is no loading indicator and the navigation bar title is empty.

The webview generates some events we can tap into. First, we need to change the declaration of the WebViewController to tell the compiler it understands these events. Open WebViewController.h and change the @interface line to:

17

To use native navigation we’re going to tap into an event webView:shouldStartLoadWithRequest:navigationType: (what a mouthful). You need to implement this method in your view controller and return YES or NO depending on whether you want this request to continue. To use native navigation we’re going to do a little trick: we will trap the request and cancel it but as we get the destination address, we’ll use it to configure and push a new view controller to the stack.

When the webview is created, set its delegate to the containing view controller.

19

And implement the shouldStartLoadWithRequest as follows:

23

You can now see the browsing activity follows the regular iOS conventions and you can go back pressing the button or swiping from the left edge.

21

To set the view title to the document title, implement the webViewDidFinishLoad: delegate method that is called when the loading finishes. After that, it is just a matter of getting the document.title using a little Javascript.

24

The title from the document is now set as the navigation bar title.

25

To implement a loading indicator, we can use the standard loading status bar indicator. On loading start we set the indicator to visible and hide it when loading stops.

26

As you can see it is now visible when there is some loading activity.

And this concludes this simple guide how on to do native container for your web app, a mini clone of Phonegap. It shows that with some care you can avoid using resource-heavy frameworks and that doing a little native code doesn’t byte you :)

The BBC web site is a little heavy and slow to load, but this is only an example. A custom web app should be much faster.

The source is available at Github.

Interested in an Android version of this guide? Coming soon!

Liked this guide and want to learn more? Check out my Clear Hybrid Apps ebook.

2014-03-30 16_43_57

John Young

É impossível ler sobre astronautas e não ficar impressionado com a história de John Young.

Duas missões Gemini, em que uma delas (Gemini 3) foi o primeiro voo tripulado de uma Gemini. Duas missões Apollo, 10 e 16, em que pisou a lua na segunda. Duas missões no Shuttle, em que o primeiro foi o STS-1, o primeiro voo de teste do primeiro shuttle, o Columbia.

Como se isto não bastasse, foi também o primeiro a levar uma sandocha para o espaço

John Young (Wikipedia)

John Young astronaut - Wikipedia, the free encyclopedia

 

Overtour: FAQ

Reuno aqui algumas perguntas que me vão fazendo sobre o meu projecto Overtour. Se tiverem curiosidade em saber mais, deixem comentário e tentarei responder logo que possa. :)

O que é o Overtour?

O Overtour é um sistema que permite utilizar um smartphone como guia multimédia num museu, jardim ou outro espaço semelhante. O nome é um trocadilho com a palavra Overture.

Como?

Os audio-guias tradicionais foram a nossa inspiração, pelo que uma das funcionalidades principais é poder reproduzir uma pista de áudio sobre a exposição, mas utilizando um smartphone conseguimos disponibilizar muito mais e melhor informação sobre uma exposição, complementando os suportes físicos.

Podemos mostrar mais informação textual sobre uma peça, utilizar a fotografias ou ilustrações para chamar a atenção para os detalhes ou mostrar como a peça foi no passado ou num enquadramento diferente. Sugerir um roteiro para a visita, mostrar um mapa do local, indicar o que está disponível para venda na loja do museu, fazer questionários didáticos sobre o conteúdo visitado.

Como surgiu?

A ideia surgiu uns dias antes do Codebits 2011. Juntei uma equipa, fizemos um protótipo rudimentar nas 48h do concurso, composto por uma API, app para iPhone e Android. Ganhámos um dos prémios, e depois do evento continuámos a desenvolver a ideia (com o apoio do Codebits Labs). Na edição de 2012 do Codebits, fomos novamente premiados face ao desenvolvido durante o ano.

O nome inicial do projecto foi mytour.

O que já fizeram?

Dois guias para o Museu Nacional de Arte Antiga (link1, link2), feitos para duas exposições temporárias, sob a forma de site mobile web. Tiveram uma aceitação bastante positiva a julgar pelo feedback e número de visitas.

O que estão a fazer neste momento?

A terminar o backoffice e a app de iPhone. A app de Android está a ser desenvolvida.

O que têm planeado?

Numa primeira fase, backoffice, API, app iPhone e app Android. O backoffice deve ser simples o suficiente para que seja possível a um museu criar e publicar os seus guias na nossa plataforma de forma autónoma. Apps simples mas funcionais.

Numa segunda fase, acrescentar suporte iPad na versão iOS e fazer app para Windows Phone. Versão web dos guias. A nível de backoffice, criar novos templates de guias, incluindo guias de realidade aumentada.

Como são as apps?

As apps são 100% nativas, desenvolvidas nas tecnologias da plataforma. O conteúdo é servido como HTML mas auxiliado por uma camada nativa que esbate as diferenças entre ambientes. Escolhemos esta abordagem depois de tentarmos muitas outras que falharam. Esta é simples, flexível, rápida e possível de se transpor para outras plataformas.

You get what you pay for

The chargers are rated from 1 to 5 energy bolts, with 5 bolts the best. The overall rating below is the average of the ratings in nine different categories, based on my measurements of efficiency, power stability, power quality, and power output. The quick summary is that phone manufacturers provide pretty good chargers, the aftermarket chargers are worse, and $2 counterfeit chargers are pretty much junk. Much to my surprise, the HP TouchPad charger (which isn’t sold any more) turned out to have the best overall score. The counterfeit iPhone charger set a new low for bad quality, strikingly worse than the other two counterfeits.

Ken Shirriff’s blog: A dozen USB chargers in the lab: Apple is very good, but not quite the best

 

 

The special one

V

Faz hoje seis meses que fui pai.

Não sei bem como comentar estes seis meses, pelo que serei simples e breve: foram bons.

As coisas boas são mesmo muito boas. As coisas más não são assim tão más. É como ter um milhão de gatinhos fofinhos concentrados numa única criatura.

Espero que se torne numa pessoa boa, decente e curiosa, mas que parta a loiça quando tiver que ser.

Se for um geek como o pai ainda bem, se não for tudo bem também. Há só uma coisa em que eu gostava que fosse igual ao pai: que quando chegar a sua vez de segurar ou ver rir os seus filhos, seja capaz de se sentir tão afortunado como eu me sinto.