Create Apps - NFP! (not for programmers!)
This book was written by Fabio Ricci Special thanks to Alessia Silvestri
2. Before you start 7. Creating a book catalog 34. Extending the book catalog 65. Deploying the book catalog 79. Currency converter, a more dynamic application 96. Creating a view-based application 116. Creating a To-Do application 139. Geo-Local application 155. Create an e-book application 195. Distributing applications All trademarks, trade names, services marks and logos referenced herein belong to their respective companies
1
Before you start
2
Make sure you have updated your mac’s operative system to its latest version. You should see an icon in your dock. This is the app store for your mac (red arrow) from which you can buy and download apps for your Mac. Once you have entered the store, search for xcode (blue arrow) 3
Select the xCode application, (obviously) named “Xcode”
4
Buy the application. Remember, if you have a subscription to a developer program, you do not have to buy xCode, which is free for registered developers. If you are a registered developer go to your member area from developer.apple.com and download xCode from there! Since the file is 4.5GB, the download may take several hours. The installation should be painless but could take a few minutes. As with all new things, patience is key! 5
Although you could find Dashcode under the installation directory, use spotlight to be sure that you launch Dashcode - xCode4
Now, use the spotlight and search for Dashcode. Launch it and keep the icon in the dock. You will use it several times from now on!
6
Creating a book catalog What you will learn What an XML file is Why is it so important to an iPhone app How to create an application from the browser template How to create a book catalog app How to populate parts of the browser with data from the XML file How to create new parts for the application How to apply styles to new parts
7
Go to: http://msdn.microsoft.com/en-us/ library/ms762271(v=vs.85).aspx or Google for “books.xml Microsoft�
Why do we start from the Microsoft site? Because they have the right XML file to copy and paste!
The first thing you need to have is a sort of database containing the data for the book catalog. XML is the language to use: it is the easiest way to store data for further use and modification. An XML file is just a text file. Go to the address you see above (microsoft.com) and explore the text of the books.xml file. It contains all the data for the application. All you have to do is copy the content of the XML file and start the TextEdit application on your Mac. 8
Paste the copied text in TextEdit and be sure to select Format -> Make Plain Text. This is needed as the XML file is a plain text file, not an RTF file (TextEditâ€&#x;s default extension)
9
Choose File -> Save as, and don’t forget to write the file extension as well (for example, books.xml). Save the file on your hard disk. Note that the text in the file has lost its colors. Don’t worry! Just open the file by double-clicking the copy on your hard disk and a program like xCode, Dreamweaver, or other (depending on what you installed) will open the file with coloring restored 10
Letâ&#x20AC;&#x2122;s have a closer look at the file. The first line is standard. It tells us that this is an XML file. The <catalog> element then opens, which means that from that point on we have to put everything in the catalog. The element closes at the end of the file with </catalog>
11
The book element has an attribute. This is its ID. You could actually write it as a sub-element, just like title, genre, author, etc. It doesn’t change much!
XML is a set of elements and sub-elements with a logic. The catalog element (parent element) has a sub-element <book> (child element). The book elements are siblings. The author element is the child of one of the book elements.
Inside the CATALOG element there are several <book> elements that close with </book>. Between <book> and </book> you can find all of the information in a single book (author, title, genre, price, publish_date and description). The actual information in an element is between the opening and the closing. So, as you can see, the first book’s title is “XML Developer‟s Guide”. After you close a book element, you can open another one and so on and so on. You close the file with </catalog>. You can build any kind of database with this simple system 12
Mobile Safari is the iPhone ‘s browser ! That’s why, to choose Mobile Safari means to start designing an application for the iPhone!
Let’s open Dashcode and, from the available templates, choose browser (blue rectangle). Uncheck Safari and leave Mobile Safari checked (red rectangle). The browser Template allows us to create a table-based iPhone application. Now, we can click Choose
13
It is safe to choose File-> Save as... and save the project on your hard disk. Do it several times during the development. We save the project as BOOKS in the documents folder
14
You can delete the sampleData.js file! We donâ&#x20AC;&#x2122;t need it because this is the data source provided by the template
Click on the small icon below, as indicated by the red arrow. All of the files in the project will be revealed. Now, from the finder, drag the XML file under the Files list. Be sure that the list appears exactly as above, with the books.xml at root level, and NOT under a directory such as Images, mobile, Parts, etc
15
Click the small icon, as indicated by the red arrow. This reveals the Data Sources of our project. After this, click dataSource, as indicated by the green arrow
16
Pay attention to the code:
../books.xml
Replace the URL of the dataSource exactly as indicated in the red rectangle (with the ../) Press ENTER on your keyboard and a representation of the first book element appears, as indicated in the green rectangle. You can find id, author, title, etc.
17
You probably want every row of the table to display the title of a book. To do this, drag a line from the small circle beside title and release it over the first ITEM on the list
18
After releasing the dragged line, choose text. This means that we want to link the title of a book to the text property of a row (where you now see Item)
19
Please note that a list icon has appeared just below dataSource
Click RUN at the top-left-hand corner of Dashcode. The iPhone simulator will run the list of the books displayed! Explore what we have done and notice that the rows display the 12 exact titles of the XML file. Now we have to manage the selection and display the details. This is our next task
20
Using placeholders, like â&#x20AC;&#x153;Genreâ&#x20AC;? is always good practice!
After you have stopped the Simulator by clicking Stop (where we clicked Run), click detailLevel, as indicated by the red arrow. This way you can manage the detail view. Next, click the List icon, as indicated by the green arrow. This reveals the elements of the XML file, but, this time, under the selection list (green rectangle). You can change the text of the text labels as in the red rectangle. Just double click on them and write something like Genre in place of Location to set the placeholders 21
After you have clicked list, you can see all of the sub-elements of a selected book item. In this case you can see the first one. Drag a line from the small circle beside the element Title to the Title label
22
You can do the same with Genre: just drag a line from the circle next to genre and drag it to the label where you want this particular info to be displayed. Do the same for the description as well
23
Run the app and select the first title in the table. The detail view is invoked and it displays the title again, the genre of the book and the description! Try other titles in the table and see what happens! We are not finished: there is more info in our XML file. Letâ&#x20AC;&#x2122;s display it Stop the simulator to do this! 24
We want to display the book IDs in the table, just below the title of the books, in each row of the main table. As indicated by the green arrow, select the listLevel to go back to the table. Select the first cell (not the item label) and resize it, making it taller 25
Every value we want to display in the table can be found in the dataSource. Values for the detail view, however, can be found under list
Make sure the library is displayed. If not, select Window -> Show Library. From the library, drag a Text element below the first Item label (red arrow). Next, select dataSource (blue arrow) and then link the circle beside id to the new text label you have just placed (green arrow). Choose text from the pop-up list. You can then run the simulator and see that the table has the ID of each book! 26
Complete the task of displaying all the values of the XML file. We can stop the simulator and go back to the detailLevel, as indicated by the red arrow
27
From the Data Sources, select list. Drag three Text Labels from the library and place it under the Description Label. You can leave some space between the three labels.
28
Connect the values of price, publish_date and author with the three new labels. Always select the text value from the pop-up list after releasing the lines on each label
29
While running the simulator, select one item and you will see that all the details are now in the detail view. What is really missing is a sort of style. Stop the simulation and go back to listLevel, as indicated by the red arrow
30
Remember: change the text with a double click on text label! Fill and Stroke of elements is to be changed in the inspector! Play with them until you are comfortable with the process
You may want to change the header of the table. Double click on it and write “Book Catalogue”. Now click on the rectangle where the header is and, from the inspector, select the second tab (fill and stroke) from the left (red arrow). Under style, select SOLID, the licorice color and opacity 75%. If you don’t see the inspector, just select window -> show inspector. Do the same with the back button and give it the solid licorice color 31
You can apply a different style to the labels of the detail view as well. This can be done by selecting a label and going to the text properties in the inspector. Here, we can change the font, style, color, size, etc. of the text in each label
32
By clicking Run, you can see the results of the styled detail view. Stop the simulator and add a field to the original XML. Letâ&#x20AC;&#x2122;s click the small icon indicated by the red arrow. This will reveal all the files in our project 33
Extending the book catalog What you will learn How to modify an XML file How to add images dynamically How to enable Google Maps How to enable Call and E-mail functionality How to apply transformation to retrieved text
34
Pay attention to the code: <image>http://url_of_the_image</image>
You can insert the element <image> (or whatever you want to name it) in each book element with the URL of an image on the internet (you can try with a couple of them to start, but each book occurrence should have an <image> element). This is the first time you are going to insert data that is not needed by a label. You have to add an image object from the library, which will show the image at that URL 35
First, you have to go back to the listLevel (red arrow). Next, make room for the image element. Let’s resize the label “Item” and move the label “Text” a few pixels to the right, just below the main label (green arrow)
36
Drag the Image element where we made room for it. If needed, resize it. As the green arrow shows, the image element must be within listRowTemplate (that is the image that will be inside the cell)
37
Remember, if you add something to the table you have to choose dataSource under Data Sources. If you add something to the detail level then you have to choose List!
Now, tell your project that the XML has changed. Click the small icon indicated by the red arrow. Go to the URL field (green rectangle) and press Enter. The XML will refresh. As you can see, there is a new element (blue arrow)
38
Drag a line from the small circle beside the image element value and select the image element. Now, choose SRC. You have just indicated that the source (SRC) of this element (and not the text) is the value of the image element
39
Itâ&#x20AC;&#x2122;s easy to add an image in the detail view. Just go to the detailLevel and place an image element. Remember, in this case, that you will have to link the image element of the XML file from the List, not the dataSource!
If you run the simulator, you see two small images. The question mark on the third and fourth cells are due to the fact that they are not present in the XML file. This problem leads us to an intelligent solution. When an image is simply not present (as a book with a missing cover) you can create a small white image for it with the image editor of your choice! 40
Reveal the files of the project by clicking the small icon as indicated by the green arrow. Drag the white.png (or whatever you name the small white image) in the images folder
41
Remember ../Images/ white.png is a relative path starting from main.js
Pay attention to the code: <image>../Images/white.png</image>
Letâ&#x20AC;&#x2122;s add an <image> element in the third and fourth book elements of the XML file (which we previously selected). Rather than indicate an absolute URL on the web, letâ&#x20AC;&#x2122;s write ../Images/white.png. This is very important: you just embedded a local file in your project! 42
As you may have noticed, the question mark has gone away! But wait. It is simply because the first title is too long for the label. Letâ&#x20AC;&#x2122;s resolve this issue!
43
First, select the cell (the white rectangle with the Item, text label and the image in it) and make it taller to make room for long titles. Then, select the Item label and make it twice as tall. The result should be exactly as shown above.
44
Now, select the Item label and, in the inspector, select the T section and Alignment & Spacing (red arrow). Now, choose ON as the value of Text Wrap
45
You also have to make sure that the image loaded by the XML file fits the size of the image element. Select the latter and, from the inspector, (attributes, green arrow) choose Size to Fit as value of Sizing. This is obviously up to you. Choosing Size to Fit the iPhone will resize the image exactly to the dimensions of the image element. 46
The simulation should now be ok! If not, play with the dashcode until you are satisfied!
47
One more thing about the style of your application. Go to the detailLevel (red arrow) and select the background of the view (red arrow). Now, in the inspector, under Fill & Stroke, choose Color as Fill and a color for the background
48
The detail level looks like the screenshot! We need the image here as well! Letâ&#x20AC;&#x2122;s add it since we know how
49
IMPORTANT: You may see all of the elements align one under the other: this is the document flow. If you want to change it, go to the Inspector (third tab) and select absolute layout. However, we advise against this!
Reach the detail level (green arrow) and drag an image element from the library, just below Genre.
50
First, select list (green arrow) and choose the third small icon (red arrow). From the representation of the XML file, drag a line from the small circle beside image to the new image element
51
It’s looking better! But there is a problem: look at the price (5.95). We did not indicate the currency! Let’s transform the label value from “5.95” to “Price: 5.95$”
52
Select the Price Label and, from the inspector, choose the fifth tab (red arrow). Under Value Transformer (green arrow), write priceTransformer (an arbitrary name for the function that will perform the transformation). Then, accept the name by pressing Enter 53
The main.js file will be revealed. There is a new function (price transformer) in the blue rectangle and just above it you will find an example provided by Apple (itemDescription). Let’s examine the itemDescription example (red rectangle). The value, which is dynamic, is embedded within a string that does not change. So, while the value can change, “The scenery in” and “is amazing in this time of year!” always remain the same. With this is mind, build your own function. 54
Pay attention to the code: return “Price:” + value + “$”;
So, let’s write “Price:” + value + “$”; just after return, This means that what is surrounded by double quotes remains the same and the value coming from the XML file can change (it’s outside the double quotes but between two + symbols) 55
Great! Every selection will now have the price properly displayed! Next, you will add some interactivity. You may want to add the bookstore address where the book can be found and see it on Google Maps after having clicked on a button! To do this, letâ&#x20AC;&#x2122;s go back to the XML file and add an <address> element 56
Pay attention to the code: <address>1 Infinite Loop, Cupertino, CA, United States</address>
Go back to the XML file and add an address element to the first book (please remember that every book element should have all the sub-elements as well. For now, letâ&#x20AC;&#x;s only add the new element to the first book in the XML)
57
Just like you did to reveal a new XML element, reach the dataSource (red arrow) and click in the URL field, then press Enter to refresh the XML file. You will see a new field, address
58
First, choose List (red arrow), because you are adding something at a detail level. Then, drag a map button to the view (blue arrow). Finally, letâ&#x20AC;&#x2122;s connect the new XML element with the button, choosing ADDRESS and not text (green arrow)
59
Run the app: choose the first book and click the map button at its detail level. We are brought to Google Maps exactly on the specified address. By taking advantage of the possibilities offered by Google Maps, you could even get directions from where you are to the localized spot (red arrow). But what if we want to call or mail the bookstore? Letâ&#x20AC;&#x2122;s add another XML field to the first Book element (you should do it for every book occurrence!) 60
Pay attention to the code: <tel>10123456789</tel> <email>info@bookstore.com</email> <subject>info: XMLâ&#x20AC;&#x2122;s developer Guide</subject>
Add three fields to the first book element in the XML file: a telephone number, an e-mail address, and the subject of an e-mail. At the same time, add two buttons from the library, the call button and the mail button.
61
After having refreshed the XML file (click on dataSource and press enter in the URL field), choose List. We now have three new elements in the XML representation. Connect the tel element to the call button and choose phoneNumber. Connect the email element to the Mail button and choose emailaddress. Finally, connect the subject element to the mail button and choose subject 62
We canâ&#x20AC;&#x2122;t simulate the click-to-call function on the simulator and we can simulate the sending of an e-mail. Click the e-mail button in the first detail view: you will see the mail application ready to send an e-mail to the specified address with the specified subject 63
You have finished your first tutorial. What you created is astonishing: starting from a simple database written in XML, you created a complete bookstore application, full of details about books and interactivity. Itâ&#x20AC;&#x2122;s now time to build the iPhone application. From now on, we have to deploy the project. Donâ&#x20AC;&#x2122;t forget to Save the whole project! 64
Deploying the book catalog What you will learn How to deploy the project onto the net How users will add it to their home screen How the application is saved on the iPhone
65
Choose the small icon as indicated by the red arrow, then Application Attributes (green arrow). Give a Title and manage the Viewport options. We suggest that you not allow users to adjust the page to fit. Be sure to check “use custom icon”. As the blue arrow indicates, don’t choose the off-line availability if you plan to often update your XML file remotely ! 66
Letâ&#x20AC;&#x2122;s associate an icon to our application. Choose Web Clip Icon (red arrow) and drag an image from the finder inside the black frame. Then, arrange the image until you are satisfied with it.
67
Itâ&#x20AC;&#x2122;s not enough! Open your index.html file and somewhere between <head> and </head> write exactly this: <link rel="apple-touch-icon" href="/mobile/Images/WebClipIcon.png">
68
Now click on Test & share (green arrow) and then on Run & Share (blue arrow). Next, click Save to Disk... and choose a location on your hard disk
69
On the hard disk, you may notice that a new directory has been created with all of the files of our project
70
Please note: itâ&#x20AC;&#x2122;s not necessary to upload files onto your web ser ver through Dashcode. You can use an FTP client to upload the file you saved on your hard disk
If you click on Deploy, rather than Save to disk, you can upload all the files to a web space you own on the internet. Letâ&#x20AC;&#x2122;s practice this as well. Make sure you have enough web space. Under destination, add an FTP or a MobileMe account. Then, simply click Deploy and in a few seconds the files will be uploaded onto your web space 71
You have just published your iPhone webapplication. You can give this URL to everyone. However, this is a web application and can not distribute through App Store
When the deploying is finished, you will be able to see the internet address where your project is. We now have our project both on-line and on our hard disk. You can now close Dashcode and start the iPhone simulator (if you have no idea where it is placed, find it with spotlight writing simulator!) 72
Start Safari on the iPhone simulator and insert the url of your web application in the address bar
73
Isn’t it great?! Now, add the web application to your home screen. Users won’t always have to give the URL of the web application! Click the symbol as indicated by the red arrow
74
choose Add to Home Screen!
75
The iPhone proposes the name of the application with the icon
76
The application is now installed and the icon will remain in the home screen! It will even work off-line, but, in this case, it obviously wonâ&#x20AC;&#x2122;t update. This can be done once you re-launch it on-line
77
Cool! We have finished our first application! It’s time to go a bit deeper with our “programming for the rest of us”!
When you re-launch the app, you will notice that it is full-screen, just like an iPhone application!
78
Currency converter, A more dynamic application What you will learn How to apply what you know to a practical case How to create a currency converter with rates extracted from a public XML How to execute basic operations in code
79
Your next application is a currency converter from euros to the most common currencies. You will use a live and public service from the Central European Bank. This will ensure that the conversion is accurate and updated. This example shows how to use the retrieved data in a dynamical way!
80
Go to www.ecb.int/stats/eurofxref/eurofxref-daily.xml and explore the source of the XML file (in Google Chrome you have to choose “View Source”). Take a few minutes to explore how the file is built. It’s quite easy. You need the RATE and CURRENCY attributes of the CUBE element to perform the conversion
81
Start a new project and choose the Browser template. Letâ&#x20AC;&#x2122;s give the same address of the web service from the European Central Bank (red rectangle) as a Data Source of the project. Remember to press Enter to refresh data. Expand the element Cube until you see the two attributes Currency and Rate 82
Connect the small circle beside currency to the first Item, choosing text. In this way, the browser will list all the currencies for which the conversion is available. Try to run the project!
83
The first time you run the project, Dashcode will warn you that the data source file is not on the same server where the application is. For security reasons, you simply canâ&#x20AC;&#x2122;t have the application on a server while the dataSource is coming from another application because you would be stealing data. However, every currency is now displayed properly in the list 84
Now, stop the simulation and let’s go edit the detail level. At the end of the process, it should look like the screenshot above: two labels in the white section, with placeholder text Currency and rate, a text field, a button with labeled Convert and another text label with € as a placeholder. Now, let’s connect the rate value (from LIST, as we are in the detail level) to the rate label and the currency value to the currency label. Every time we connect, make sure you choose text from the pop-up list 85
Name the elements properly. This will help us when we get our hands dirty with javascript! Select the Currency label and, in the Inspector, under Attributes, give currencyLabel as an ID (with no white spaces). Change the ID of the rate Label to rateLabel and the â&#x201A;Ź label to euroLabel. Also, change the ID of the textField to toConvertField. Pay particular attention to capital letters 86
Now, ask yourself? What do I have to do to make sure that the conversion takes place? Easy enough. Click on the Convert button. Then select it and go in the Inspector, under Behaviors. We need the onClick event because the button will be clicked. Letâ&#x20AC;&#x2122;s write convertNow as Handler of this event and press enter 87
After having clicked Enter, you are taken to the main.JS file inside a new function, called convertNow. Itâ&#x20AC;&#x2122;s here that the conversion will take place
88
If you had not used the parseFloat function we would have extracted simple strings. We need numbers to calculate the final result!
Pay attention to the code: function convertNow(event) { var rates = parseFloat(rateLabel.innerText); var euros = parseFloat(toConvertField.value); }
Note that to extract the value of a text label we used .innerText, while to extract the value of a text field we used .value
You have written two lines of code. The first one declares a variable, rates, which parse the float number of the label string, whose ID is rateLabel. In the second one, we declare a variable, euros, which parse the float number of the text field string, whose label is toConvertField 89
Pay attention to the code: function convertNow(event) { var rates = parseFloat(rateLabel.innerText); var euros = parseFloat(toConvertField.value); var result = euros*rates; }
Next, declare the variable result, which will be euros * rates
90
Pay attention to the code: function convertNow(event) { var rates = parseFloat(rateLabel.innerText); var euros = parseFloat(toConvertField.value); var result = euros*rates; euroLabel.innerText = result.toString().substr(0,7); }
Finally, set the inner text of the label, whose ID is euroLabel. The result is the value result (declared in the previous line) converted to a string with .toString(). With .substr(0,7) you choose to only print the first 7 digits of the result 91
The result is pretty good! You choose a currency, give the amount of euros in the text field and, after having clicked the convert button, print the result in a label. Since the source is always updated on the internet, we are ensured to always have the current values of the conversion
92
One more thing about optimization: if you click in the text field to insert the amount of euros to convert, you will note that the application will zoom. This is especially not needed in this case
93
Choose Application Attributes and be sure to uncheck the page zooming. This way the application will never zoom. Obviously, if you need the users to zoom the application, you can leave the page zooming checked and set the maximum zoom allowed. Itâ&#x20AC;&#x2122;s up to you! 94
As an exercise, make this application more iPhone-like! Use all the tricks you learned in the first tutorial (adding colors, value transformers, etc.). When you are comfortable with it, you will be ready to go on with our course. Itâ&#x20AC;&#x2122;s great that you can create useful applications with a few clicks. This way you can focus on the graphical part, rather than on the programming! 95
Creating a view-based application What you will learn What a stack layout is How to add views to the stack layout How to manage transitions between views How to manage transition effects Data persistence using HTML5
96
The next steps teach you how to create more views (or pages) for your application. We will build a simple application with two pages that reach each other with stunning iPhone-like transitions! Choose a new project, Custom template and click Choose. 97
Choose the only two elements (content and footer) and get rid of them (select and delete), so that the project is graphically empty
98
From the library, under parts, drag a Stack Layout and resize it to the whole canvas
99
Under Stack Layout (red arrow) you will see two views. Click on view1
100
Go to the inspector and under “Fill & Stroke”, choose “Color as Fill” and choose a background color. You are coloring the first view
101
Drag a text label on the first view and change the text to “First View”
102
Drag a Lozenge Button from Parts Library and change its label to â&#x20AC;&#x153;Go to 2nd Viewâ&#x20AC;?
103
Go to the second view (red arrow) and reproduce the same situation, with the exception of the labels of the text and the button
104
Go to the first view. Select the button and, in the Inspector, under Behaviors, onClick write â&#x20AC;&#x153;goTo2ndViewâ&#x20AC;? (as handler for the event) and press Enter. A new function was created for you in main.Js 105
Go to the library and under Code among the snippets of code ready to be used, choose Set StackLayout Current View (red arrow). Now copy the code (blue arrow) and paste it inside the newly created function. Dashcode gives the code, ready to change from one stack layout view to another 106
Do the same for the second view button . Select second view, then the button and write “goTo1stView” as handler of the onClick event. Now, in the newly created function, write the same code but change “view2” to “view1”. (blue arrow)
107
Run the simulator and click the button. When you are in the second view, go back. As you can see, the viewsâ&#x20AC;&#x2122; transition was set by default. It is pushed from right to left
108
Letâ&#x20AC;&#x2122;s see where you can set the style of the transition. Click stackLayout (red arrow) and in the inspector, under Attributes, change to another style of transition (blue arrow). Try all of them! They are simply gorgeous! Good. Now try to run the simulator every time you change the style of transition! 109
Let’s extend the application and introduce an important concept: the local storage. It is one of the new capabilities of HTML5. First, go to the second view and drag a text field on it. Select it and in the inspector, under Attributes, give it a new ID “saveField”. Now, in the goTo1stView function write: localStorage.myName = saveField.value You are saving the content of saveField for the key myName for when we go back to the first view 110
In the first view, drag a text label and make sure it’s empty. Drag a button as well and change its label to “load”
111
Select the empty label and change its ID to loadLabel, under the inspector - attributes (red arrow)
112
Select the â&#x20AC;&#x153;loadâ&#x20AC;? button and in the inspector, under behavior, give loadName as handler of the onClick event and press Enter. A new function is created. Write loadLabel.innerText = localStorage.myName inside it 113
Run the simulator and give your name in the text field. Then, click the button and go to the first view.
114
In the first view, click the “load” button and you will see the name you gave in the second view. What have you done? Easy enough: you saved a string for the key myName and loaded its value. The great thing is that whenever you launch the application, without having to set the name again in the second view, click “load” in the first view. The value stays on the phone, just like in a database! 115
Creating a To-Do application What you will learn Data persistence with HTML5 How to save and load data How to add and manage a gauge to measure something Hot to warn users with alerts
116
Now that we know how to save strings, letâ&#x20AC;&#x2122;s see how we can build a proper to-do list. There will be a text-area where we write what we have to do and a button to save it. Every time you will start the application you will automatically see the text we saved. Letâ&#x20AC;&#x2122;s start a new custom project and get rid of the content and the footer 117
Letâ&#x20AC;&#x2122;s drag a text area from the library to the view and resize it properly, leaving some space at the bottom
118
Now, drag a button just above the text area and change the label to â&#x20AC;&#x153;Saveâ&#x20AC;?
119
Select the text area and open the inspector. Under attributes give the “toDoArea” ID to the text area
120
Select the button and type save in the inspector, under behaviors, as handler for the onClick event. Press enter and a new function will be created
121
Inside the new function write: localStorage.todo = toDoArea.value; This is used to set the content of the text area of the key todo in the localStorage (the local storage of our iPhone)
122
In the function load() (which is created by Dashcode for every application and manages what is happening at the start of the application) let’s write toDoArea.value = localStorage.todo; This means that every time we start the application on the same device, the text area content will be the same as the saved key “todo”, which we saved in the save function. 123
If you are starting the application for the first time, you have never set the key todo for the local storage. The iPhone will set â&#x20AC;&#x153;undefinedâ&#x20AC;? as content of the text area. This error has to,(obviously) be managed in someway!
124
Just before the text we just inserted, in the load() function add this line, if (localStorage.todo) This means that what follows this line is applied only if the object localStorage.todo was defined. If not, then nothing happens! 125
add alert(„ToDo list was saved!‟) in the save(event) function, This will create an alert every time we save our todo list. Without this alert the user doesn’t have a confirmation that the new text was saved 126
Remember that, when using applications with text inserted by users, the â&#x20AC;&#x153;allow users to adjust page zoomâ&#x20AC;? should be deselected. This is because every time someone writes in the text area, the application will zoom
127
Try to run the simulator now and write something in the text area
128
Save and see that an alert will tell you that the list was saved! Now, close the simulator
129
Start the simulator again and see that the text area already has the saved content! You are now ready to deploy your project on to the web. You will have a todo list on your server, ready to be used by every user. Remember that the local storage is on the usersâ&#x20AC;&#x2122; iPhone, so everyone will see his own local storage! Itâ&#x20AC;&#x2122;s time to extend our application! 130
You may now need to add a stress-calculator to your to-do list. If there arenâ&#x20AC;&#x2122;t many things to do the indicator will be green. If they reach a normal level it will be orange, if there are too many things to do, then the display will be red. Drag a Gauge from the library and make sure the default values are kept in the inspector, under attributes. The value of gauge is between 0 and 100: more than 1 and it will be green; more than 50 and it will be orange; more than 80 and it will be red. Keep this in mind! 131
In the save function write: if (toDoArea.value.length < 100) gauge.object.setValue(10) That is, if the length of the text is less than 100 characters, then set the value of the gauge to 10. In this case it will be green. 132
If you run the simulator and write some text, for example Hello World, and press Save, the gauge will turn green
133
Let’s complete the three possibilities. If the characters are more than 200, let’s set the value of the gauge to 90 (it will be red). Note that if there are two conditions (more than 100 but less than 200 characters) the if needs “((“ and you must insert “&&” between each condition. 134
Run the simulator and write about 3 lines and press save. The gauge will turn orange
135
Add more lines and press Save. The gauge will turn red! You are definitely too busy!
136
In the save function, set another key (gaugeValue) for the localStorage and make it just like the value of the object. localStorage.gaugeValue = gauge.object.value;
137
Set the value of the gauge like the gaugeValue saved key of the localStorage in the load function, which you can find at the start of the application,. This way, when you press save, you set the gauge value in the localStorage. The next time you start the application, the value of the gauge will be set correctly as well. gauge.object.setValue(localStorage.gaugeValue); 138
Geo-Local application What you will learn Geo location with HTML5 How to retrieve your position and show it in Google Maps How to get directions from your position to a given address How to alert users with warnings
139
Letâ&#x20AC;&#x2122;s explore the geo-location capabilities of the iPhone. What about a simple application that shows where we are on Google Maps. A kind of magic that is very easy to implement! Start a new custom project!
140
Drag a simple button in the view and set its ID to getLocation in the inspector -> attributes
141
With the button selected, go to Behaviors in the Inspector and write getGoogleMaps as handler of the onClick event, and press Enter. A new function will be created
142
Pay attention to the code: function getGoogleMaps(event) { if (!navigator.geolocation) { alert(‘a warning, that geo-location is not supported’); } }
Let’s suppose that the geo localization is not supported by the iPhone. This should not, however, be the case
143
Pay attention to the code: else { navigator.geolocation.watchPosition(displayCoordinates); return false; } }
In else, write exactly what you see in the screenshot. This calls a function, displayCoordinates, after having started the watchPosition function of the iPhone
144
Pay attention to the code: function displayCoordinates(curPos) { var Latitude = curPos.coords.latitude; var Longitude = curPos.coords.longitude; }
Create the function displayCoordinates(curPos) and declare the Latitude and the Longitude. This is always the same, no matter what you are going to create
145
Pay attention to the code:
location.href=‘http://maps.google.com?q=’+Latitude+’,’+Longitude; q is introducing the values of latitude and longitude! This depends on Google Maps API.
Insert the Google maps address. After the value q= we have to indicate the latitude and longitude, separated by a comma. You may have them as coordinates but we insert them as variables
146
Start the simulator and make sure that you are on-line
147
You will receive a warning that Google Maps wants to use your current location
148
Here we are! The iPhone just found us! You can now use all of Google Maps’ functions because you are on the Google Maps WebSite. You are now ready to extend your application a bit. Since we know the destination address, let’s calculate the directions from your current location! 149
Drag a search field from the library to the view and give it â&#x20AC;&#x153;destinationAddressâ&#x20AC;? as an ID in the inspector -> attributes. In this search field you will write the destination address. Try to add a placeholder in the attributes as well. This will explain what it is for 150
Now, drag a button just below the search field. In the Inspector, under Behaviors, make â&#x20AC;&#x153;getDirectionsâ&#x20AC;? the handler for the onclick event. As soon as you press Enter a new function will be created 151
Paste the exact content of the getPosition function in the new function. Make sure you replace displayPosition with displayDirections. In fact, we need another function to find directions from where we are to a given address in the search bar 152
Pay attention to the code: dAddress = destinationAddress.value; var Latitude = curPos.coords.latitude; var Longitude = curPos.coords.longitude; location.href=‘http://maps.google.com?saddr=’+Latitude +’,’+Longitude+’’&daddr=’+dAddress; return false
Write the new function, displayDirections, exactly as you see it above. First, we set a variable named dAddress that is the content of the search field. Then, we retrieve the latitude and longitude of your location. We then give Google two parameters: saddr, which is the start address and daddr, which is the destination address 153
Try to run the simulator, but, be aware that it is better to deploy your project on the web and reach the address with a real iPhone! The simulator may crash in your test if it reaches the Google Map website
154
Create an e-book application What you will learn How to work with large amounts of text How to manage view transitions How to save and load a bookmark How to add a pop-up menu How to deploy an application for off-line usage
155
www.gutenberg.org/ cache/epub/76/pg76.txt
First, go to www.gutenberg.org with your browser and find the page of a book in plain text. If you want to follow our suggestion, copy the URL as you can see in the screenshot above. You will reach the plain text of the Adventures of Huckleberry Finn which is a good text for our experiment 156
Eliminate the content and footer, we want a totally empty application to start from.
157
Next, drag and drop a Stack Layout in our partsâ&#x20AC;&#x2122; browser. Donâ&#x20AC;&#x2122;t forget to leave some pixels at the top for the navigation menu and a couple of buttons to add later. Save the application with a name
158
Expand the arrow beside stackLayout and change the name of the two views to ChapterOne and ChapterTwo
159
Now, select the stackLayout and go to the inspector, under Attributes. Here, click the “+” symbol and add ChapterThree. You may also want to change the Transition Style
160
Select the ChapterOne view and drag a text Label onto the view, exactly to the top (not the top of the window!)
161
Copy the first chapter in the gutenberg project page and paste it inside the text label, replacing the Text word that was in it
162
Select the text part (red arrow) and in the inspector, under Fill&Stroke choose “color as fill” and “white” as the color. The background will be set on white
163
In the inspector, under Text, â&#x20AC;&#x153;alignment & spacingâ&#x20AC;? choose the icon that justifies the text
164
Go to the inspector once again, under Text, Character. Choose a color and a font that you like. We chose tungsten as the color of the text
165
Now, letâ&#x20AC;&#x;s choose Metrics from the inspector and add the left and right margin. Set both of them to 5 pixels, just like the screenshot. The two margins have been created
166
All this kind of modification are simply a matter of style. Choose your own style suiting your needs and taste! But remember to apply the style to all the chapters!
Finally, choose ChapterOne under the partsâ&#x20AC;&#x2122; browser and fill it with the white color (in the inspector -> Fill&Stroke)
167
Now, do exactly the same thing for ChapterTwo and ChapterThree views. Obviously, every chapter must have a different text, therefore, copy and paste the second and third chapters respectively for the second and the third text labels
168
Make sure that the popup is OUTSIDE of the stackLayout in the partsâ&#x20AC;&#x2122; browser
You may want a selector for the chapters of the book. The best way to do this is to drag and drop a Pop-up menu from the library to the top of the windows: this will be common to all three views!
169
With the popup selected, go to the inspector and then under attributes. Change the labels and most of all the values of the possible popup choices. Just double click on what you want to change. Be sure that at least three values are the same as what you see above 170
Pay careful attention! The button must also be outside the stackLayout! To position it beside the pop-up menu, you have to change its layout to absolute!
Next, let’s drag and drop a button and change its label to something else, like “go”
171
With the button selected, go to the inspector and then, under Behaviors, add the handler selectChapter for the onClick event. After pressing enter, a new function will be created
172
In the new function we copy and paste the methods exactly like the part where we dealt with transitions from view to view. Pay attention: we do not give the ID of the view to reach, but popup.value. That is the value of the pop-up menu. If we choose Chapter 2 from the menu, the value will be ChapterTwo (you set it in the inspector). The application will then reach the view named ChapterTwo! 173
Before you try everything to see that it is working properly, go to the application attributes and deselect the “allow users to adjust page zoom”. At this point we don’t really need a zoom!
174
Now run the application and choose a chapter!
175
For example, this is how you select chapter three
176
If the users want to reach the top menu while they are scrolling the page, they can just press the status bar at the top (red arrow). Try it yourself!
177
You may need a way to save a bookmark so that the reader can start reading from where he left off. Select the first TEXT (red arrow) from the partsâ&#x20AC;&#x2122; browser, just below ChapterOne. In the inspector -> Behaviors write saveBookmark as Handler of the onClick event. Press enter and a new function will be created. When the user taps the text, the bookmark will be set 178
Pay attention to the code: function saveBookmark(event) { localSotrage.pageOffset = window.pageYOffset; localStorage.chapterSaved = popup.value; }
Set two keys for the localStorage. The pageOffset key will save the value of the vertical scroll (window.pageYOffset). The chapterSaved key will save the name of the chapter
179
Pay attention to the code: console.log(localStorage.pageOffset); console.log(localStorage.chapterSaved);
To be sure that the saved values are properly set, print them in the log
180
Run the application and scroll the text a bit in chapter 1. Now tap in the text and pay attention to the log. Something similar to the red rectangle will appear
181
It is a good idea to give the user a warning that a bookmark has been set!
182
Run the simulator again and tap somewhere in the scrolled text of chapter one. You will now see a warning
183
Associate the “saveBookmark” function to the other chapters as well. Select all of the Text (like in the red arrow) and under “inspector” -> “behaviors” write saveBookmark(event) and press enter. In this way all of the chapters can be tapped to save the bookmark 184
Now, let‟s drag a button and place it beside the one we already have. In the “inspector”, under behaviors give “loadBookmark” as the handler for the onclick event. Press enter and a new function will be created 185
Pay attention to the code: function loadBookmark(event) { if (localStorage.chapterSaved) { var stackLayout = document.getElementById(‘s tackLayout’).object; stackLayout.setCurrentView(localStorage.chapterSaved) console.log(localStorage.chapterSaved); }; }
First, see if localStorage.chapterSaved exists (if a bookmark was set). Then we call the current view of stackLayout, whose name is the same as the saved chapter
186
Pay attention to the code: if (localStorage.pageOffset) { window.scroll( 0, localStorage.pageOffset) console.log (localStorage.pageOffset); };
Inside the same function, check if the localStorage.pageOffset exists. If yes, then the app will scroll the page to where we saved!
187
Go to chapter two in your simulator (the one you just ran). Then, click on Load and...
188
...the user will be taken exactly to the point where he saved the bookmark in chapter one!
189
You are not finished. What if the reader is not on-line? Go to “Application Attributes” and select “Allow offline viewing of this web application”
190
Deploy the application on your server (â&#x20AC;&#x153;Run & Shareâ&#x20AC;? from the left menu) and write down its URL
191
Go to the application on-line with your iPhone or the simulator (through safari, NOT running from dashcode) and add the application to the home screen
192
You will find the icon of the application in the home screen (we didnâ&#x20AC;&#x2122;t set it, but you are free to do it, like in the book catalog example). Run the application now by tapping on the icon and make sure your iPhone or Mac (if you are using a simulator) has no internet connection 193
The application will work like a charm! Now you can read the e-book even if you donâ&#x20AC;&#x2122;t have an active internet connection!
194
Distributing applications What you will learn Where to go after the development Get your application listed by Apple
195
An application, no matter what kind, is published when it is on the web. You wonâ&#x20AC;&#x2122;t be a part of the Apple circle (App Store). You can still buy some ads on Google, AdMob or other mobile advertisement service. However, you can submit your application to Apple to be reviewed, that way it will be seen on Appleâ&#x20AC;&#x;s web apps page. You will get much more traffic this way! 196
You can browse the apps at www.apple.com/webapps. You can browse by categories. You want to have your app listed here, donâ&#x20AC;&#x2122;t you?
197
Submitting your app is pretty simple. You need an Apple ID, that you probably own. If not, get it from the Apple website. Go to www.apple.com/webapps and click on â&#x20AC;&#x153;submitting applicationsâ&#x20AC;?.
198
Read the agreement carefully and, if you agree, accept the terms and conditions
199
You will be prompted to give some basic info about your application
200
You have to add a screenshot of your app on the same page. Make a screenshot that is 320x436 pixel and is less than 1MB. Save it as a JPEG image because t has the best ratio between quality and size! Next, you have to add an icon, which is 128x128 pixels. This info you provide will help you list your application in the right directory so you can catch the userâ&#x20AC;&#x;s attention. Be creative. When you are finished, click on submit... and good luck! 201
Hope it was helpful!
202