Showing posts with label Tutorials. Show all posts
Showing posts with label Tutorials. Show all posts

MacSupport - Tips

Get Mac OS X Support, Tips, Tricks, Tutorials, Guides & How To's right in to your Mac OS X Dashboard.
↓ Download

LionTips

Get Mac OS X 10.8 and 10.7 Tips, Tricks, Tutorials, Guides & How To's right in to your Mac OS X Dashboard.
↓ Download

Mac Tips and Tricks

Get all Mac OS X Tips, Tricks, Tutorials, Hacks, Support, Downloads, Updates...right in to your Mac OS X Mountain Lion, Lion, Snow Leopard, Leopard or Tiger Dashboard !
Learn How To using Finder, Preview, iChat, iCal, Mail, Safari, Address Book, Expose, Dock, Dashboard, Spotlight, Keyboard Shortcuts...or Customizing Your Mac !
↓ Download

WebKit Open Source Project

Here are some demo web applications that display various web technologies supported by WebKit.

Offline Calendar
Picking up where the sticky notes example leaves off, the Offline Calendar demo goes much more in depth into the power of the HTML 5 database API.
By storing the user's calendar events in a local databases and caching the application resources themselves using the HTML 5 application cache the calendar can be used with no network connection!

CSS Transitions and Transforms
This demo shows off how straight forward it is to add transforms and implicit animations to a web application by adding a small amount of CSS.
Check out our blog posts about CSS animations and CSS transforms for more details and examples.

Editing Toolbar
The editing toolbar shows off a rich HTML editing toolbar in WebKit. It uses JavaScript and CSS to fade in and out and to implement the buttons that apply text formatting and alignment. Click in the text area to see the toolbar appear.

Sticky Notes
Referenced about adding HTML 5 structured database storage, this is a simple example of how the database API works in the form of persistent yellow sticky notes.
Storing simple data, it is a great way for developers to introduce themselves to how the database API works.

Base SDK Missing


For the noobie iPhone App Developer, their reaction to the error message “Base SDK Mssing” on an xCode sample code project, is similar to how I once felt about the “Blue Screen of Death” on a PC.

I got that same feeling of frustration when I loaded down the PageControl sample code from Apple. I couldn’t test the sample code in xCode because the “Base SDK Missing” error message was on display. I was using xCode 3.

It wasn’t the first time I’d come across this error, however, previously I’d found a solution.  I was desperately seeking a solution to paging horizontally and having PageControl.

I’ve solved my problems with the “Base SDK Missing” error message by trawling the internet and finding many generous people who share their knowledge.  So this “post” is me giving back to the app development community a little of what I’ve learned.

Solving the “Base SDK Missing” Error

Sometimes you will try to open an old xCode project and you will find you can’t open it because the file gives you a “Base SDK Missing” message, as shown in the image below:

 Base SDK Missing error message as seen on the xCode Dashboard

The first time I came across this problem I was working through John Ray’s Book “iPad Application Development in 24 hours”. The problem raised its ugly head again when I tried to open the PageControl sample code from Apple.

I came across the problem again when I found an article about sample code titled “How to Add A Slick iBooks Like Page Turning Effect Into Your Apps”, published by Johann “John” Dowa on his website ManiacDev. The article led me to a download for an xCode project called Leaves created by Tom Brow and an extension of the same project called “Leaves Two Pages” by Ole Begemann.

I couldn’t open the projects because they gave an error message i.e. Base SDK Missing.  As mentioned, I’d had this message before but when I applied my solution, Solution 1, shock horror, it didn’t work.  So I hunted around the internet for more solutions and found Solution 2.  Both solutions are set out below:

Solution One for xCode 3
1) Select xCode File Name in the left side navigation bar and click on the blue Info button on the xCode Dashboard and a drop down menu will appear showing several tabs.

Screenshot showing selection of xCode File Name


xCode Dashboard Info Button

xCode Dashboard

2) Click on the Build Tab

Info Button Drop Down List showing Build Tab

3) Find “Base SDK” under Architecture section and select the appropriate version e.g. 4.2
4) Scroll down to Deployment Section and also set “OS Deployment Target” as 4.2
5) Close the xCode Project (do not close the xCode Program) then reopen the Project

This solution came partly from a member of the iPhone SDK Development Forum and a little tweaking by me.

If this did not fix the problem then follow the steps in solution two, as follows:
Sometimes, if the test file has been created in a very old xCode Program,  you need to take more steps.
A solution for this problem was solved by a member of the “Leaves Developers” Google Group.

Solution Two
1) In xCode go to Targets and right click over the file name and select “Get Info”

Target Get Info Drop Down Menu

2) A drop down list will appear. Go to the Architecture section and click on the Base SDK Value field and select the correct iOS.

Target Architecture Drop Down Menu

3) Close the xCode Project (do not close the x Code program) and reopen the project.  Hopefully you will then see that the Base SDK Missing message has disappeared and you are seeing “Simulator …

Simulator Button on the xCode Dashboard

Xcode Development



NSTableView class to create a single column table view

1. Create an Xcode project
  • Step 01: Launch Xcode 3.0 and create a new project by clicking on File ⇒ New Project.
  • Step 02: Select Application ⇒ Cocoa Application and click on the Next button.
  • Step 03: Specify the Project Name and Project Directory as follows:
  • Project Name: SingleColumnTableView
  • Project Directory: ~/Documents/Project/XCode/Tutorial/SingleColumnTableView/
  • Click on the Finish button.
This will bring up the Project window.

2. Edit the NIB file
  • Step 01: In the Groups & Files browser, expand the NIB Files folder and double click the MainMenu.nib file.
This will launch the Interface Builder application and open the following windows:
  • a. Interface Builder NIB file browser
  • b. Interface Builder Inspector
  • c. Interface Builder Library
  • d. Application Main Menu window
  • e. Application Window

3. Create a controller class
  • Step 01: Use Xcode to create the application controller class. In the Groups & Files browser, right click on the Classes folder ⇒ Add ⇒ New File.
  • Step 02: Select Cocoa ⇒ Objective-C class and click on the Next button.
Specify a name for the application controller class and click on the Finish button.
  • Filename: ApplicationController.m
You should now be able to see the files for the ApplicationController class will be automatically added to the Xcode project.

Double click on the ApplicationController.h file to view its interface specifications.

Double click on the ApplicationController.m file to view its implementation details.
  • Step 03: Click on the Interface Builder icon to bring it to the foreground. Using the Interface Builder Library, select Objects & Controllers ⇒ Controllers ⇒ NSObject and drag it to the Interface Builder NIB file browser.

Using the Interface Builder Inspector, specify the following information:
  • Class Identity ⇒ Class: ApplicationController
  • Interface Builder Identify ⇒ Name: ApplicationController
Because Interface Builder is automatically synchronized with Xcode, you can see the ApplicationController class that was previously created in Xcode, in the drop-down list box for the class identify.

You should now be able to see the reference to the ApplicationController class in the NIB file browser as shown below.
  • Step 04: Specify an action that the application controller class can respond to.

Go to Class Actions, click on the button and specify an action called update:
  • Step 05: Specify an outlet that will be used by the application controller class to communicate with the target table view object.
Go to Class Outlets, click on the button and specify an outlet called tableView.

Leave the tableView type as id for the moment. The tableView type will be changed to NSTableView later on.

4. Create a table view and link it to the application controller class' outlet
  • Step 01: Using the Interface Builder Library, click on the Objects tab and select the Views & Cells ⇒ Data Views folderr
  • Step 02: Drag and drop an NSTableView object from the library to the application window. Resize the NSTableView object so that it is correctly positioned within the window. Leave a little space at the bottom of the window, so that we can later on, add a button to update the table view contents.
  • Step 03: Since we're going to create a single column table view, we will need to delete the second table column using the Interface Builder NIB file browser.
Expand the Window (Window) object till you reach the Table View node.

Select the second Table Column and delete the object using the menu option Edit ⇒ Delete.

Your application window should now contain a single column table view.
  • Step 04: Slowly click on the NSTableView object twice, to select the Table View object.
The first click will select the Scroll View object and the second click will select the Table View object. The Table View will be highlighted as shown below.

Ctrl+drag from the Table View object to the ApplicationController class to specify its dataSource and delegate outlets.

Right click on the Table View object to check the newly created associations for its dataSource and delegate outlets.
  • Step 05: Select the ApplicationController class and ctrl+drag to the Table View object to its tableView outlet.
Right click on the ApplicationController class to check the newly create association for the tableView outlet.

Using the Interface Builder, change the type for the tableView outlet to NSTableView.


5. Create a button and link it to the application controller class' update action
  • Step 01: Using the Interface Builder Library, click on the Objects tab and select the Views & Cells ⇒ Buttons folder.
  • Step 02: Drag and drop an NSButton from the library to the application window.
Select the button and click on it once to rename it to Update.
  • Step 03: Select the Update button and ctrl+drag to the ApplicationController class in the Interface Builder NIB file browser.
Right click on the ApplicationController class to check the newly create association for the update: action.


6. Automatically generate source code and merge changes for the ApplicationController class
  • Step 01: Select the ApplicationController in the Interface Builder NIB file browser and click on File ⇒ Write Class Files.
Browse to the folder: ~/Documents/Project/XCode/Tutorial/SingleColumnTableView
Click on Save.
Click on Merge. This will launch the FileMerge utility.
  • Step 02: Merge changes to the ApplicationController.h file.
Select the ApplicationController.h file using the FileMerge utility.
This will show the ApplicationController.h source code differences between the
  • a. new source code that we just automatically generated using Interface Builder, on the left hand side
  • b. previous source code that we had initially generated using Xcode, on the right hand side
  • Difference #1: Select the first difference by pressing the ↓ down arrow key. We want to keep the changes on the right side so, press the → right arrow key. Alternatively, you can use the Actions drop down list to choose the difference to be selected for inclusion in the final merge.
  • Difference#2: Select the difference on the left, since we don't want the extra line break.
  • Difference#3: Select the difference on the left, since we want the IBOutlet NSTableView *tableView; entry to be included in the final merge.
  • Difference#4: Select the difference on the left, since we want the - (IBAction)update:(id)sender; entry to be included in the final merge.
Save the merge by clicking on File ⇒ Save Merge. You should see a green tick mark next to the ApplicationController.h file.
  • Step 03: Merge changes to the ApplicationController.m file.
Select the ApplicationController.m file using the FileMerge utility.

This will show the ApplicationController.m source code differences between the
  • a. new source code that we just automatically generated using Interface Builder, on the left hand side
  • b. previous source code that we had initially generated using Xcode, on the right hand side
  • Difference #1: Select the difference on the right.
  • Difference#2: Select the difference on the left, since we don't want the extra line break.
  • Difference#3: Select the difference on the left, since we want the - (IBAction)update:(id)sender; entry to be included in the final merge.
Save the merge by clicking on File ⇒ Save Merge. You should see a green tick mark next to the ApplicationController.m file.

Combine the files by selecting Merge ⇒ Combine Files.

Open the ApplicationController.h file to view the merged changes.

Open the ApplicationController.m file to view the merged changes.


7. Add a data source for the table view
  • Step 01: Open the ApplicationController.h file and add a data source.
Add the following lines of code just after the interface declaration:
  • // Data source
  • @private NSMutableArray *aBuffer;

8. Implement NSTableView protocol methods for displaying table view contents
  • Step 01: Implement the protocol method to retrieve the total number of rows in a table view.
Add the following lines of code to the ApplicationController.m file:
  • - (int)numberOfRowsInTableView:(NSTableView *)tableView{
  • return ([aBuffer count]);
  • }
  • Step 02: Implement the protocol method to retrieve the object value for a table column.
Add the following lines of code to the ApplicationController.m file:

  • - (id)tableView:(NSTableView *)tableView
  • objectValueForTableColumn:(NSTableColumn *)tableColumn
  • row:(int)row{
  • return [aBuffer objectAtIndex:row];
  • }

9. Implement the Update button handler
  • Step 01: Implement the ApplicationController update: method to print a log message to a console window and add a string object to the table view.
Add the following lines of code to the update: method in the ApplicationController.m file:
  • - (IBAction)update:(id)sender {
  • NSLog(@"The user has clicked the update button");
  • [aBuffer addObject:@"HelloWorld"];
  • [tableView reloadData];
  • }

10. Implement the awakeFromNib and dealloc methods
  • Step 01: In the awakeFromNib method, implement code to create and allocate memory for a new mutable array object.
Add the following lines of code to the ApplicationController.m file:
  • - (void)awakeFromNib{
  • aBuffer = [NSMutableArray new];
  • [tableView reloadData];
  • }
  • Step 02: In the dealloc method, implement code to release memory allocated to the mutable array object.
Add the following lines of code to the ApplicationController.m file:
  • - (void)dealloc{
  • [aBuffer release];
  • [super dealloc];
  • }

11. Build and run the application
  • Step 01: Display the Xcode console window by clicking on Run ⇒ Console.
  • Step 02: In the Xcode project window, click on the Build and Go icon to build and launch the application.
  • Step 03: Click on the Update button. This will create a row entry in the table view.
View the resulting log messages on the console window.

Document version: 1.0
Document date: 2008-03-08
Document reference: XCT_NSTVSC-1.0


Development tools: Xcode 3.0, Interface Builder 3.0.
Operating system: Mac OS X 10.5.2 (Leopard)


Handling button events

1. Create an Xcode project
  • Step 01: Launch Xcode 3.0 by clicking on the Xcode application icon.
  • Step 02: Click on File ⇒ New Project
  • Step 03: Select Application ⇒ Cocoa Application and click on the Next button.
  • Step 04: Specify the Project Name and Project Directory as follows:
Project Name: HandlingButtonEvents
Project Directory: ~/Documents/Project/XCode/Tutorial/HandlingButtonEvents/

Click on the Finish button.

This will bring up the Project window.

2. Edit the NIB file
  • Step 01: In the Groups & Files browser, expand the NIB Files folder and double click the MainMenu.nib file
This will launch the Interface Builder application.

The Interface Builder (IB) application will display a set of windows for developing a Human Machine Interface (HMI):
  • a. Interface Builder NIB file browser
  • b. Interface Builder Inspector
c. Interface Builder Library
d. Application Main Menu window
e. Application Window

3. Create a controller class
  • Step 01: We will now use Xcode to create the application controller class. In the Groups & Files browser, right click on the Classes folder ⇒ Add ⇒ New File.
  • Step 02: Select Cocoa ⇒ Objective-C class and click on the Next button.
Specify a name for the application controller class and click on the Finish button.

Filename: ApplicationController.m

You should now be able to see the files for the ApplicationController class will be automatically added to the Xcode project.
Double click on the ApplicationController.h file to view its interface specifications.

Double click on the ApplicationController.m file to view its implementation details.
  • Step 03: Click on the Interface Builder icon to bring it to the foreground. Using the Interface Builder Library, select Objects & Controllers ⇒ Controllers ⇒ NSObject and drag it to the Interface Builder NIB file browser.
Using the Interface Builder Inspector, specify the following information:

Class Identity ⇒ Class: ApplicationController
Interface Builder Identify ⇒ Name: ApplicationController

Because Interface Builder is automatically synchronized with Xcode, you can see the ApplicationController class that was previously created in Xcode, in the drop-down list box for the class identify.

You should now be able to see the reference to the ApplicationController class in the NIB file browser as shown below.
  • Step 04: Specify an action that the application controller class can respond to.
Click on the button and specify an action called update:

Using Interface Builder, click on File ⇒ Write Class Files to to update the source files for the application controller class.

Click on the Save button.

Click on the Replace button to overwrite the existing application controller class files.

Double click on the ApplicationController.h file from the Xcode project browser window.

Observe the newly added action method entry in the interface file
  • - (IBAction)update:(id)sender;
Double click on the ApplicationController.m file from the Xcode project browser window.

Observe the newly added action method implementation entry in the implementation file
  • - (IBAction)update:(id)sender {
  • }
  • Step 05: Implement the update action method for the application controller class.
As an example, add code to the ApplicationController.m implementation file to print a debug log message to a console window.
  • - (IBAction)update:(id)sender {
  • NSLog(@"The user has clicked the update button");
  • }

4. Create a button and link it to the application controller class' update action
  • Step 01: Using the Interface Builder Library, click on the Objects tab and select the Views & Cells folder.
  • Step 02: Drag and drop an NSButton from the library to the application window.
Select the button and click on it once to rename it to Update.
  • Step 03: Select the Update button and ctrl+drag to the ApplicationController class in the Interface Builder NIB file browser.
Select the update: in the Recieved Actions pop-up window.

Select the Update button and view the button connections using the Interface Builder Inspector.

Select the ApplicationController class from the Interface Builder NIB file browser and view the application controller class connections.


5. Build and run the application
  • Step 01: Display the Xcode console window by clicking on Run ⇒ Console
This will bring up the Xcode console window.
  • Step 02: In the Xcode project window, click on the Build and Go icon to build and launch the application.
This will launch the application window.
  • Step 03: Click on the Update button.
View the resulting log messages on the console window.

Use Photos from iPhoto !

Use your Mac Desktop as a large digital frame of sorts. You can show favorite pictures from albums you've created in iPhoto, and have them change every so often, too.

Open System Preferences (in the Apple menu). Click Desktop & Screen Saver (in the first row). This will bring-up settings for Desktop wallpaper and Screen Saver. Then, click the Desktop tab.

If the left column of the settings windows, you'll see a number of folders from which you can choose images to be displayed on the Mac Desktop.

Toward the bottom of the list, iPhoto Albums is listed. Click the triangle to view the albums you've created in iPhoto. Select one of the albums. Your Desktop will change instantly, displaying a photo from the album.
Now, in the same window, check the "Change picture" setting and choose when or how often you'd like the Desktop wallpaper to change. For example: every 30 minutes. You can click the "Random order" setting to have the next Desktop picture randomly selected from the iPhoto album.

One final finesse. In the settings window, above the thumbnail photos, you can specify how you'd like the photo to display on the Desktop: Fit to Screen, Fill Screen, Stretch to Fill Screen, Center and Tile. Play with the options and select what you like best.

Change your Screen Saver

Your desktop picture is the most high-profile item on your computer. Likewise, your screen saver is the most high profile item when you're not. And like the desktop picture, you can change the default screen saver, use your own slideshow creation, or use a third-party screen saver.

To swap your current screen saver for another one:
Mac OS X contains several preinstalled screen savers
  1. From the Apple menu, choose System Preferences to open the System Preferences window.
  2. Click the Desktop & Screen Saver button to display its preferences.
  3. Click the Screen Saver tab to display just the Screen Saver preferences. All installed screen savers appear in the left pane. The right pane displays a preview of the selected screen saver.
  4. Click one of the Screen Saver items in the left pane to select it for use.
  5. If you'd like, click Test to see what the screen saver will look like in use.
To create a slideshow screen saver, do one of the following:
By selecting Library, your Mac will automatically create a slideshow screen saver made from your iPhoto pictures.
  1. In the Screen Saver preferences window, select Library or one of the two choices below it to turn your iPhoto images into a slideshow screen saver.
  2. In the Screen Saver preferences window, select Pictures Folder to display the images in it, or select Choose Folder, navigate to and select a folder that contains images in the resulting dialog, then click Choose to put it in use.
    To add a third-party screen saver:
    Once you install a third-party screen saver, either through an installer or manually,
    you can select it just like you would with the preinstalled ones.
    1. If the screen saver doesn't have an installer to place the file in the right folder, locate the .saver file in the package.
    2. Drag the file into the Screen Savers folder, which is in the Library folder at the root of your hard disk ~/Library/Screen Savers.
    3. Follow the steps in "swap your current screen saver for another one," above, to select the third-party screen saver.

    Customize your Screen Saver
    Now that you've selected a new screen saver, you can further customize its settings. Here are some of the things you can do in the Screen Saver preferences window.
    1. Click Options to view the selected screen saver's user-configurable display settings and adjust them to your liking. These settings will vary screen saver to screen saver.
    2. Move the "Start screen saver" slider left or right to change the time, in minutes, at which the screen saver begins to play.
    3. If you'd like the ability to start the screen saver manually, click Hot Corners. In the resulting dialog, choose Start Screen Saver from any of the four corner pop-up menus and click OK. The screen saver will start when you move your arrow to your chosen screen corner.
    4. If you're the adventurous type, select "Use random screen saver," and your Mac will automatically select a screen saver when it goes into screen saver mode.

      MacWall Tips

      1. Get The Right Resolution
      Regardless of its artistic beauty, a wallpaper that doesn’t come in a high enough resolution and matching aspect ratio will look grainy and distorted. To avoid awkward looking background images, you should understand the specs of your monitor before you start hunting for great wallpapers.
      Screen resolutions are denoted in pixels, e.g. 800 x 600. The numbers indicate how many pixels your monitor can display horizontally (800) and vertically (600). The resolution also reveals that the monitor in this example has an aspect ratio of 4 : 3 (horizontal : vertical pixels).

      A perfect wallpaper has to meet two criteria:
      1. high enough resolution
      2. matching aspect ratio
      This article from CrunchGear provides a resolution chart (depicted below) that lets you pick the right wallpaper aspect ratio and resolution for your monitor. For example, if your monitor has a resolution of 1600 x 1200 you have a 4:3 aspect ratio. This ratio is color-coded red, so you can use all resolutions in red that are 1600 x 1200 or greater.


      So how do you find out your monitor’s native resolution and aspect ratio?

      Windows 7
      Right-click on the desktop and select > Screen resolution from the menu and look for the number next to > Resolution:

      Windows XP
      Right-click on the desktop, select > Properties from the menu and switch to the > Settings tab. You’ll see a slider under > Screen resolution in the bottom left.



      2. Find the Most Beautiful Wallpapers
      The amount of websites that offer free wallpapers is endless. Fortunately, you came to the right place and we have already done some weeding out for you. You can either get some fresh wallpapers from our themed compilations or find your own favorites in the resources we have covered.

      Wallpaper Compilations:
      Wallpaper Resources:


      3. Shuffle Your Wallpapers
      Now that you have skimmed through all those resources, you’re left with dozens of wallpapers you like and you cannot make up your mind. Don’t despair because you don’t have to! Rather than settling for just one wallpaper, why not use all of them?

      Windows 7
      If you have Windows 7 Home or up, you can personalize your computer and that includes your desktop. Right-click on the desktop and select > Personalize. In the bottom left of the window that opens click on > Desktop Background. From > Picture Location: select the folder where you stored your wallpapers or click > Browse… to add a custom folder. Select all the images you want to use, then select the > Picture position define to > Change picture every… and check > Shuffle to not see the same sequence every time. Finally click > Save Changes and enjoy.

       

      Windows XP
      Windows XP doesn’t offer an inbuilt tool to shuffle your wallpapers. However, there are many third party applications that can do that trick. I have been using ScrollWall and I also like John’s Background Switcher. Another super fascinating wallpaper tool with a social twist is Wallcast
      All aforementioned applications and several more are described in these articles:


      4. Create An Unobstructed View Of Your Wallpaper/s
      So you have this fantastic wallpaper or maybe you have already set up shuffling, but what is it that you see on your desktop? Lots of icons! To really enjoy the view, you need to get rid of them! BEFORE vs AFTER IMAGE I have written two articles that will guide you to a beautifully organized and minimalist desktop:


      5. Get An Animated Desktop Wallpaper
      My final advice should be: keep it simple. However, if you have resources to spare, go ahead and get yourself an animated desktop wallpaper. In Windows 7 you can use your screensaver as a wallpaper. To use a video of your own you have to convert it to an .scr (screensaver) file.



      Windows 7
      Windows XP

      Game Development - Tutorials


      Unity Widgets


      Building
      Besides regular Mac apps, Unity can build MacOSX widgets, using the Unity web plugin.


      Customization

      The widgets are just a web player wrapped with the widget HTML. If you right/option-click on the .wdgt file and select Show Package, you'll see the generated Unity file and accompanying HTML, CSS and images. Any additional files loaded by the widget can be added in the widget. For example, this widget streams a movie, cat.ogv.
      You will probably want to customize the default Unity build by replacing the Icon.png file, which is the icon that displays in the Dashboard dock. Version information can be adjusted in the Info.plist file. You can customize the back panel by modifying the HTML and CSS files.


      Publishing
      Most widgets are submitted and listed on the Apple widget download page. Most widgets are free, though some are listed as shareware. If a widget is listed as a Staff Favorite or Featured Widget, it certainly ends up in the Top 50.


      Widgets published include HyperBowl Classic, FuguBowl, FuguMaze, FuguTilt, FuguFlip, Fugutype...
      Other Unity widgets include 3D Paradise Paintball, MacPinball, Banana Warehouse and Blingy.

      References
      See the Apple Dashboard developer article for an overview of widget and links to more articles.

      Dashboard Widget Tutorial

      This tutorial walks you through using Dashcode to create a Dashboard widget. As you follow the steps, you learn how to choose a widget template, customize your widget’s appearance and code, and share your widget with others. Completing this tutorial is a quick and easy way to get started building Dashboard widgets in Dashcode.

      This document includes two additional tutorials, “Mobile Safari Web Application Tutorial” and “Dual-Product Web Application Tutorial,” which follow this one. The remainder of the document delves more deeply into the Dashcode development environment, describing how it supports both widget and web application development. If you don’t want to learn how to create a web application, you can continue learning more about Dashcode by reading “Starting a Project.”

      Before You Begin !

      In this tutorial, you build a Dashboard widget that counts down to your birthday, similar to the widget shown in Figure 1-1.

      Figure 1-1  The Birthday widget



      Before continuing, make sure that you have Dashcode installed on your Mac (the location is /Developer/Applications/). If you don’t have Dashcode installed, read “Getting and Running Dashcode” to learn how to get and install Dashcode.


      Choose a Template


      To start, double-click the Dashcode icon to open it. A new project window opens and displays a dialog in which you first select the type of project you’re interested in—in this case, Dashboard—and then, the kind of widget you want to create from an assortment of templates. Templates are handy starting points for creating common types of widgets. Select a template’s icon to show a short description of what that template does.

      To make the Birthday widget, this tutorial uses the Countdown template. Select its icon and click Choose. A project window opens with a new widget based on the Countdown template, as shown in Figure 1-2.

      Figure 1-2  A project window showing a new Dashboard widget


      Along the left side of the project window is the navigator, which you use to switch between the various tools available when you’re designing a widget. The main portion of the window is the canvas, which you use to design your widget’s interface.

      At the bottom of the navigator in Figure 1-2 you can see the Workflow Steps list, which guides you through the widget development process. Each step is a milestone in creating a widget, telling you what to do and where to do it. When you complete a step, mark it as done and move on to the next step.

      Note: If you don’t want to see the Workflow Steps list, you can hide it by choosing View > Steps or by clicking the button that looks like a checkbox at the bottom edge of the project window (this button is highlighted in Figure 1-2).
      Alternatively, you can view a list of the widget’s files in place of the Workflow Steps list. If you want to see the Files list, choose View > Files or click the list button in the bottom edge of the project window (it’s the button that looks like a bulleted list).
      Set the Target Date

      The Countdown template gives you a Dashboard widget with all the elements and code needed to count down to an event. All you need to do is tell the widget the target date. To set the target date, select Widget Attributes in the navigator. The canvas is replaced by the widget attributes pane, in which you specify important values that your widget needs.

      In the Properties section of the widget attributes pane, choose Date and Time in the Target Kind pop-up menu and enter the date of your next birthday, as shown in Figure 1-3.

      Figure 1-3  The Countdown template’s properties





      Test the Countdown

      Your new Dashboard widget is already fully functional. To prove this, choose Debug > Run to run the widget. Dashcode can run a widget without opening it in Dashboard, making it a handy place to test your widget and fix any problems you encounter. After the widget loads, it starts counting down towards your next birthday.

      When you’re satisfied that your widget is working as you expect, choose Debug > Stop to stop it.

      Now is a good time to save your widget project. Choose File > Save to save the project. Give your project a name and select a location to save it in. Your widget is saved in a widget project that encapsulates the widget and information Dashcode needs to create the widget for you.


      Customize the Widget’s Appearance

      Although you now have a fully functioning Dashboard widget that’s ready to share, you might want to personalize it to make it unique. Dashcode’s design tools make it easy to customize your widget’s interface. Select the widget item in the navigator (it should display the name you gave it when you saved the project). The widget attributes pane is replaced with the canvas.

      First, change your widget’s body color. Select the widget body (also called the front image or frontImg) on the canvas and then choose Window > Show Inspector. The inspector window allows you to modify a selected element’s properties, such as its appearance and behavior. Click the Fill & Stroke button at the top of the inspector window (it’s the second from the left). If it’s not already selected, click the Style tab to reveal fill, stroke, corner roundness, and opacity values. Click the color well and choose a new color in the Colors window that appears. Try different fill styles until you find a combination that you like. If you want to try changing other effects, such as the glass appearance, click the Effects tab to reveal these values, as shown in Figure 1-4.

      Figure 1-4  Tweaking the front image using the Fill & Stroke inspector



      When you’re finished customizing your widget’s body, add a photo of yourself from iPhoto to the widget. Your iPhoto library is available from the Library window. To show your iPhoto library, choose Window > Show Library; then click the Photos button. Find a photo and drag it to your widget on the canvas. Resize it by dragging any of the resize handles on the photo.

      Finally, change the Event Label text to something like “...days until my birthday.“ You can do this by selecting the Event Label text, clicking the Attributes button in the inspector window (it’s the leftmost button), and entering the text in the Value field, or by double-clicking the text in the widget body itself and entering the new text.



      Add Functionality Using Parts

      Now that you have a personalized Dashboard widget that counts down to your birthday, add a button that, when clicked, shows the Apple Store (so your friends and family can buy you a birthday present!). To add a button to your widget, use a button part. Parts are controls and views used on a widget’s interface.

      To find a button part, choose Window > Show Library and click Parts. You can use the search field at the bottom of the window to help you find a particular part or type of part. From the list of parts, drag the Lozenge Button part from the Library window to your widget’s body. Double-click the button to select its label text, enter the text “Buy me a gift” and press Return. You'll probably need to resize the button to fit the new label.



      Write Code to Show the Apple Store

      To make the button take the user to the Apple Store when it’s clicked, you need to add a behavior to the button. In the inspector window, click the Behaviors button (it’s the rightmost button). This shows the Behaviors pane, in which you assign handler functions to events on an object. Select the button on the canvas and double-click in the Handlers column next to the onclick event name. Enter the name of a new function, such as showAppleStore, and press Return. Click the arrow next to the function name you entered to reveal the source code editor below the canvas. Here you write code to add functionality to your widget. Clicking the arrow reveals the showAppleStore function Dashcode inserted in your widget’s code. Between the braces ({ .. }) enter the following line of code:

      widget.openURL("http://store.apple.com/");


      The code in the source code editor should look like that in Figure 1-5.



      Figure 1-5  A function in the source code editor



      Test your widget again by choosing Debug > Run. Click the button you added and make sure a new Safari window opens with the Apple Store website displayed. Be sure you save your project often to preserve the changes you make.




      Deploy Your Widget

      Congratulations! You’ve created your first complete Dashboard widget using Dashcode.

      To open your widget in Dashboard, choose File > Deploy Widget. Click Install in the dialog that appears to view your widget in Dashboard.

      To share your widget with the world, select Run & Share in the navigator. The pane that appears displays the widget project name you chose in “Test the Countdown,” but you can replace this with a different name if you want. You can also set the minimum version of Mac OS X your widget should run in. Click Save to Disk to save your widget. You can now email it to friends or post it on your webpage. You can use the File > Compress command in the Finder to archive it.

      Dashboard Widget Tutorial

      This tutorial walks you through using Dashcode to create a Dashboard widget. As you follow the steps, you learn how to choose a widget template, customize your widget’s appearance and code, and share your widget with others. Completing this tutorial is a quick and easy way to get started building Dashboard widgets in Dashcode.

      This document includes two additional tutorials, “Mobile Safari Web Application Tutorial” and “Dual-Product Web Application Tutorial,” which follow this one. The remainder of the document delves more deeply into the Dashcode development environment, describing how it supports both widget and web application development. If you don’t want to learn how to create a web application, you can continue learning more about Dashcode by reading “Starting a Project.”

      Before You Begin !

      In this tutorial, you build a Dashboard widget that counts down to your birthday, similar to the widget shown in Figure 1-1.

      Figure 1-1  The Birthday widget



      Before continuing, make sure that you have Dashcode installed on your Mac (the location is /Developer/Applications/). If you don’t have Dashcode installed, read “Getting and Running Dashcode” to learn how to get and install Dashcode.


      Choose a Template


      To start, double-click the Dashcode icon to open it. A new project window opens and displays a dialog in which you first select the type of project you’re interested in—in this case, Dashboard—and then, the kind of widget you want to create from an assortment of templates. Templates are handy starting points for creating common types of widgets. Select a template’s icon to show a short description of what that template does.

      To make the Birthday widget, this tutorial uses the Countdown template. Select its icon and click Choose. A project window opens with a new widget based on the Countdown template, as shown in Figure 1-2.

      Figure 1-2  A project window showing a new Dashboard widget


      Along the left side of the project window is the navigator, which you use to switch between the various tools available when you’re designing a widget. The main portion of the window is the canvas, which you use to design your widget’s interface.

      At the bottom of the navigator in Figure 1-2 you can see the Workflow Steps list, which guides you through the widget development process. Each step is a milestone in creating a widget, telling you what to do and where to do it. When you complete a step, mark it as done and move on to the next step.

      Note: If you don’t want to see the Workflow Steps list, you can hide it by choosing View > Steps or by clicking the button that looks like a checkbox at the bottom edge of the project window (this button is highlighted in Figure 1-2).
      Alternatively, you can view a list of the widget’s files in place of the Workflow Steps list. If you want to see the Files list, choose View > Files or click the list button in the bottom edge of the project window (it’s the button that looks like a bulleted list).
      Set the Target Date

      The Countdown template gives you a Dashboard widget with all the elements and code needed to count down to an event. All you need to do is tell the widget the target date. To set the target date, select Widget Attributes in the navigator. The canvas is replaced by the widget attributes pane, in which you specify important values that your widget needs.

      In the Properties section of the widget attributes pane, choose Date and Time in the Target Kind pop-up menu and enter the date of your next birthday, as shown in Figure 1-3.

      Figure 1-3  The Countdown template’s properties





      Test the Countdown

      Your new Dashboard widget is already fully functional. To prove this, choose Debug > Run to run the widget. Dashcode can run a widget without opening it in Dashboard, making it a handy place to test your widget and fix any problems you encounter. After the widget loads, it starts counting down towards your next birthday.

      When you’re satisfied that your widget is working as you expect, choose Debug > Stop to stop it.

      Now is a good time to save your widget project. Choose File > Save to save the project. Give your project a name and select a location to save it in. Your widget is saved in a widget project that encapsulates the widget and information Dashcode needs to create the widget for you.


      Customize the Widget’s Appearance

      Although you now have a fully functioning Dashboard widget that’s ready to share, you might want to personalize it to make it unique. Dashcode’s design tools make it easy to customize your widget’s interface. Select the widget item in the navigator (it should display the name you gave it when you saved the project). The widget attributes pane is replaced with the canvas.

      First, change your widget’s body color. Select the widget body (also called the front image or frontImg) on the canvas and then choose Window > Show Inspector. The inspector window allows you to modify a selected element’s properties, such as its appearance and behavior. Click the Fill & Stroke button at the top of the inspector window (it’s the second from the left). If it’s not already selected, click the Style tab to reveal fill, stroke, corner roundness, and opacity values. Click the color well and choose a new color in the Colors window that appears. Try different fill styles until you find a combination that you like. If you want to try changing other effects, such as the glass appearance, click the Effects tab to reveal these values, as shown in Figure 1-4.

      Figure 1-4  Tweaking the front image using the Fill & Stroke inspector



      When you’re finished customizing your widget’s body, add a photo of yourself from iPhoto to the widget. Your iPhoto library is available from the Library window. To show your iPhoto library, choose Window > Show Library; then click the Photos button. Find a photo and drag it to your widget on the canvas. Resize it by dragging any of the resize handles on the photo.

      Finally, change the Event Label text to something like “...days until my birthday.“ You can do this by selecting the Event Label text, clicking the Attributes button in the inspector window (it’s the leftmost button), and entering the text in the Value field, or by double-clicking the text in the widget body itself and entering the new text.



      Add Functionality Using Parts

      Now that you have a personalized Dashboard widget that counts down to your birthday, add a button that, when clicked, shows the Apple Store (so your friends and family can buy you a birthday present!). To add a button to your widget, use a button part. Parts are controls and views used on a widget’s interface.

      To find a button part, choose Window > Show Library and click Parts. You can use the search field at the bottom of the window to help you find a particular part or type of part. From the list of parts, drag the Lozenge Button part from the Library window to your widget’s body. Double-click the button to select its label text, enter the text “Buy me a gift” and press Return. You'll probably need to resize the button to fit the new label.



      Write Code to Show the Apple Store

      To make the button take the user to the Apple Store when it’s clicked, you need to add a behavior to the button. In the inspector window, click the Behaviors button (it’s the rightmost button). This shows the Behaviors pane, in which you assign handler functions to events on an object. Select the button on the canvas and double-click in the Handlers column next to the onclick event name. Enter the name of a new function, such as showAppleStore, and press Return. Click the arrow next to the function name you entered to reveal the source code editor below the canvas. Here you write code to add functionality to your widget. Clicking the arrow reveals the showAppleStore function Dashcode inserted in your widget’s code. Between the braces ({ .. }) enter the following line of code:

      widget.openURL("http://store.apple.com/");


      The code in the source code editor should look like that in Figure 1-5.



      Figure 1-5  A function in the source code editor



      Test your widget again by choosing Debug > Run. Click the button you added and make sure a new Safari window opens with the Apple Store website displayed. Be sure you save your project often to preserve the changes you make.




      Deploy Your Widget

      Congratulations! You’ve created your first complete Dashboard widget using Dashcode.

      To open your widget in Dashboard, choose File > Deploy Widget. Click Install in the dialog that appears to view your widget in Dashboard.

      To share your widget with the world, select Run & Share in the navigator. The pane that appears displays the widget project name you chose in “Test the Countdown,” but you can replace this with a different name if you want. You can also set the minimum version of Mac OS X your widget should run in. Click Save to Disk to save your widget. You can now email it to friends or post it on your webpage. You can use the File > Compress command in the Finder to archive it.

      Dashboard Widget Tutorial

      This tutorial walks you through using Dashcode to create a Dashboard widget. As you follow the steps, you learn how to choose a widget template, customize your widget’s appearance and code, and share your widget with others. Completing this tutorial is a quick and easy way to get started building Dashboard widgets in Dashcode.

      This document includes two additional tutorials, “Mobile Safari Web Application Tutorial” and “Dual-Product Web Application Tutorial,” which follow this one. The remainder of the document delves more deeply into the Dashcode development environment, describing how it supports both widget and web application development. If you don’t want to learn how to create a web application, you can continue learning more about Dashcode by reading “Starting a Project.”

      Before You Begin !

      In this tutorial, you build a Dashboard widget that counts down to your birthday, similar to the widget shown in Figure 1-1.

      Figure 1-1  The Birthday widget



      Before continuing, make sure that you have Dashcode installed on your Mac (the location is /Developer/Applications/). If you don’t have Dashcode installed, read “Getting and Running Dashcode” to learn how to get and install Dashcode.


      Choose a Template


      To start, double-click the Dashcode icon to open it. A new project window opens and displays a dialog in which you first select the type of project you’re interested in—in this case, Dashboard—and then, the kind of widget you want to create from an assortment of templates. Templates are handy starting points for creating common types of widgets. Select a template’s icon to show a short description of what that template does.

      To make the Birthday widget, this tutorial uses the Countdown template. Select its icon and click Choose. A project window opens with a new widget based on the Countdown template, as shown in Figure 1-2.

      Figure 1-2  A project window showing a new Dashboard widget


      Along the left side of the project window is the navigator, which you use to switch between the various tools available when you’re designing a widget. The main portion of the window is the canvas, which you use to design your widget’s interface.

      At the bottom of the navigator in Figure 1-2 you can see the Workflow Steps list, which guides you through the widget development process. Each step is a milestone in creating a widget, telling you what to do and where to do it. When you complete a step, mark it as done and move on to the next step.

      Note: If you don’t want to see the Workflow Steps list, you can hide it by choosing View > Steps or by clicking the button that looks like a checkbox at the bottom edge of the project window (this button is highlighted in Figure 1-2).
      Alternatively, you can view a list of the widget’s files in place of the Workflow Steps list. If you want to see the Files list, choose View > Files or click the list button in the bottom edge of the project window (it’s the button that looks like a bulleted list).
      Set the Target Date

      The Countdown template gives you a Dashboard widget with all the elements and code needed to count down to an event. All you need to do is tell the widget the target date. To set the target date, select Widget Attributes in the navigator. The canvas is replaced by the widget attributes pane, in which you specify important values that your widget needs.

      In the Properties section of the widget attributes pane, choose Date and Time in the Target Kind pop-up menu and enter the date of your next birthday, as shown in Figure 1-3.

      Figure 1-3  The Countdown template’s properties





      Test the Countdown

      Your new Dashboard widget is already fully functional. To prove this, choose Debug > Run to run the widget. Dashcode can run a widget without opening it in Dashboard, making it a handy place to test your widget and fix any problems you encounter. After the widget loads, it starts counting down towards your next birthday.

      When you’re satisfied that your widget is working as you expect, choose Debug > Stop to stop it.

      Now is a good time to save your widget project. Choose File > Save to save the project. Give your project a name and select a location to save it in. Your widget is saved in a widget project that encapsulates the widget and information Dashcode needs to create the widget for you.


      Customize the Widget’s Appearance

      Although you now have a fully functioning Dashboard widget that’s ready to share, you might want to personalize it to make it unique. Dashcode’s design tools make it easy to customize your widget’s interface. Select the widget item in the navigator (it should display the name you gave it when you saved the project). The widget attributes pane is replaced with the canvas.

      First, change your widget’s body color. Select the widget body (also called the front image or frontImg) on the canvas and then choose Window > Show Inspector. The inspector window allows you to modify a selected element’s properties, such as its appearance and behavior. Click the Fill & Stroke button at the top of the inspector window (it’s the second from the left). If it’s not already selected, click the Style tab to reveal fill, stroke, corner roundness, and opacity values. Click the color well and choose a new color in the Colors window that appears. Try different fill styles until you find a combination that you like. If you want to try changing other effects, such as the glass appearance, click the Effects tab to reveal these values, as shown in Figure 1-4.

      Figure 1-4  Tweaking the front image using the Fill & Stroke inspector



      When you’re finished customizing your widget’s body, add a photo of yourself from iPhoto to the widget. Your iPhoto library is available from the Library window. To show your iPhoto library, choose Window > Show Library; then click the Photos button. Find a photo and drag it to your widget on the canvas. Resize it by dragging any of the resize handles on the photo.

      Finally, change the Event Label text to something like “...days until my birthday.“ You can do this by selecting the Event Label text, clicking the Attributes button in the inspector window (it’s the leftmost button), and entering the text in the Value field, or by double-clicking the text in the widget body itself and entering the new text.



      Add Functionality Using Parts

      Now that you have a personalized Dashboard widget that counts down to your birthday, add a button that, when clicked, shows the Apple Store (so your friends and family can buy you a birthday present!). To add a button to your widget, use a button part. Parts are controls and views used on a widget’s interface.

      To find a button part, choose Window > Show Library and click Parts. You can use the search field at the bottom of the window to help you find a particular part or type of part. From the list of parts, drag the Lozenge Button part from the Library window to your widget’s body. Double-click the button to select its label text, enter the text “Buy me a gift” and press Return. You'll probably need to resize the button to fit the new label.



      Write Code to Show the Apple Store

      To make the button take the user to the Apple Store when it’s clicked, you need to add a behavior to the button. In the inspector window, click the Behaviors button (it’s the rightmost button). This shows the Behaviors pane, in which you assign handler functions to events on an object. Select the button on the canvas and double-click in the Handlers column next to the onclick event name. Enter the name of a new function, such as showAppleStore, and press Return. Click the arrow next to the function name you entered to reveal the source code editor below the canvas. Here you write code to add functionality to your widget. Clicking the arrow reveals the showAppleStore function Dashcode inserted in your widget’s code. Between the braces ({ .. }) enter the following line of code:

      widget.openURL("http://store.apple.com/");


      The code in the source code editor should look like that in Figure 1-5.



      Figure 1-5  A function in the source code editor



      Test your widget again by choosing Debug > Run. Click the button you added and make sure a new Safari window opens with the Apple Store website displayed. Be sure you save your project often to preserve the changes you make.




      Deploy Your Widget

      Congratulations! You’ve created your first complete Dashboard widget using Dashcode.

      To open your widget in Dashboard, choose File > Deploy Widget. Click Install in the dialog that appears to view your widget in Dashboard.

      To share your widget with the world, select Run & Share in the navigator. The pane that appears displays the widget project name you chose in “Test the Countdown,” but you can replace this with a different name if you want. You can also set the minimum version of Mac OS X your widget should run in. Click Save to Disk to save your widget. You can now email it to friends or post it on your webpage. You can use the File > Compress command in the Finder to archive it.

      RSS Feed Reader Widget !

      RSS Feed Reader Widget !

      RSS Feed Reader Widget !

      Build Web Apps with Dashcode

      When you first launch Dashcode (the easiest way to launch it is through Spotlight), you will see that Dashcode has already created some templates for you to build your Web applications quickly (see Figure 1).

      Figure 1: The various templates provided by Dashcode

      The best way to learn is to select each template (other than the Custom template) and examine the content of each application. When you have selected a template, examine their contents and press Command-r to test the application on the iPhone Simulator. Go ahead and have fun with each template. When you have enough fun and get yourself acquainted with the environment, come back and we shall create an iPhone Web application from scratch and you will see how each part is built.

      Building the UI
      Alright, now that you are back, create a new Custom project In Dashcode. Notice that by default, Dashcode created a content and a footer parts for you (see Figure 2). Parts are the various views that you seen on your Web applications, such as buttons, text, etc. For this section, you will create a simple currency convertor Web application for the iPhone.

      Figure 2: The parts in the Custom template

      Select each of these parts and press the delete key. We shall delete these two parts and add our own parts manually.

      Using the Library (Window'Show Library), drag-and-drop a Stack Layout part to the design surface (see Figure 3).

      Figure 3: Using the Library to drag and drop parts onto your application

      Expand the stackLayout part and you should see that it contains two subviews - view1 and view2. Select view1 and change its size to 320px by 356px (see Figure 4) via the Inspector window (Window'Show Inspector). Do the same for view2.

      Figure 4: Changing the size for view1 and view2 via the Inspector window

      Double-click on view1 and rename it as mainScreen. Do the same for view2 and rename it as settings (see Figure 5).


      Figure 5: Renaming the two subviews

      In the Library, drag-and-drop the Rounded Rectangle Shape part onto the mainScreen view (see Figure 6).

      Figure 6: Adding the Rounded Rectangle Shape part to the subview

      It its Inspector window, select the Fill & Stroke tab and in the Style tab select Gradient fill (see Figure 7) and select two colors.

      Figure 7: Using the gradient fill to fill the part

      Select the Effects tab and check the Glass and Recess checkboxes (see Figure 8).

      Figure 8: Adding glass effect to the part

      Select the Metrics tab and select the Absolute layout (see Figure 9).

      Figure 9: Using absolute layout for parts positioning



      Add the following parts to the Rounded Rectangle Shape part (see Figure 10) and name them as:

      Text
      TextField
      Pop-up Menu
      Push Button


        Figure 10: Adding additional parts to the subview

        Select the settings subview and repeat the same steps you have performed above. Figure 11 shows the parts added to the settings subview.

        Figure 11: Populating the settings subview

        You are now ready to view the application on the iPhone Simulator. Press Command-r to view the application on the iPhone Simulator (see Figure 12). Notice that the application is hosted by mobile Safari on the iPhone.

        Figure 12: Click 'Run' toView the application on the iPhone Simulator

        Notice that you can only see the mainScreen subview. To see the settings subview, you need to write some code to navigate to it from the mainScreen subview.


        Coding the Application
        So you are now ready to write some code. With the mainScreen subview selected, right-click on the Settings button and select Events'onclick (see Figure 13).

        Figure 13: Creating an event handler for the onclick event

        You will be asked to name the event handler for this event. Name it as shown in Figure 14.


        Figure 14: Naming the handler for the event

        Notice that the code editor now appears at the bottom of the designer (see Figure 15).


        Figure 15: The code editor where you can add your code


        Enter the following code:

            function btnSettings_ClickHandler(event)
            {
                var views = document.getElementById('stackLayout');
                var settings = document.getElementById('settings');
                if (views && views.object && settings) {
                    views.object.setCurrentView(settings);
                }
            }

        Select the settings subview and right-click on the Save Settings button and select Events'onclick. Name the handler as btnSave_ClickHandler. Enter the following code:

            function btnSave_ClickHandler(event)
            {
                var views = document.getElementById('stackLayout');
                var front = document.getElementById('mainScreen');
                if (views && views.object && front) {
                    views.object.setCurrentView(front, true);
                }
            }

        Test the application again by pressing Command-r. This time, you will be able to navigate to the settings view by tapping on the Settings button in the mainScreen subview (see Figure 16).

        Figure 16: Tapping on the Settings button navigates to the settings subview


        Database Access
        So far, your application displays two screens where you can perform some currency conversion as well as set the exchange rates for the different currencies. For simplicity, I am going to assume that you are converting the currencies into Singapore Dollars (SGD). All the exchange rates would be based on the SGD as the base currency.

        To allow the users to store their own exchange rates, you will make use of the local database feature as defined in HTML 5 (which is supported by Mobile Safari). Doing so allows users of your application to store the exchange rate locally on their iPhones.

        In the main.js file, add the following lines of code for performing database operations:

            var database = null;                           // The client-side database
            var DB_tableName = "CurrencyKeyValueTable";    // database name

            // Function: initDB() - Init and create the local database, if possible
            function initDB()
            {
                try {
                    if (window.openDatabase) {
                        database = openDatabase("ExchangeRatesDB", "1.0",
                                                "Exchange Rates Database", 1000);
                        if (database) {
                            database.transaction(function(tx) {
                                tx.executeSql("SELECT COUNT(*) FROM " + DB_tableName, [],
                                function(tx, result) {
                                    loadRates();
                                },
                                function(tx, error) {
                                    // Database doesn't exist. Let's create one.
                                    tx.executeSql("CREATE TABLE " + DB_tableName +
                                    " (id INTEGER PRIMARY KEY," +
                                    "  key TEXT," +
                                    "  value TEXT)", [], function(tx, result) {
                                        initRates();
                                        loadRates ();
                                    });
                                });
                            });
                        }
                    }
                } catch(e) {
                    database = null;
                }
            }

            // Function: initRates() - Initialize the default exchange rates
            function initRates()
            {
                if (database) {
                    database.transaction(function (tx) {
                        tx.executeSql("INSERT INTO " + DB_tableName +
                            " (id, key, value) VALUES (?, ?, ?)", [0, 'USD', 1.44]);
                        tx.executeSql("INSERT INTO " + DB_tableName +
                            " (id, key, value) VALUES (?, ?, ?)", [1, 'EUR', 2.05]);
                        tx.executeSql("INSERT INTO " + DB_tableName +
                            " (id, key, value) VALUES (?, ?, ?)", [2, 'AUS', 1.19]);
                    });
                }
            }

            // Function: loadRates() - Load the currency exchange rates from DB
            function loadRates()
            {
                var element;  
                var popUpElement = document.getElementById('popupConvertTo');

                if (database) {
                    database.transaction(function(tx) {
                        tx.executeSql("SELECT key, value FROM " + DB_tableName, [],
                        function(tx, result) {
                            for (var i = 0; i < result.rows.length; ++i) {
                                var row = result.rows.item(i);
                                var key = row['key'];
                                var value = row['value'];

                                //---populate the pop-up menu part---
                                popUpElement.options[i].text = key;
                                popUpElement.options[i].value = value;

                                if (key == 'USD') {
                                    element = document.getElementById('txtUSD');
                                }
                                else {
                                    if (key == 'EUR') {
                                        element = document.getElementById('txtEUR');
                                    }
                                    else if (key == 'AUS') {
                                        element = document.getElementById('txtAUS');
                                    }
                                }
                                element.value = value;
                            }
                        },
                        function(tx, error) {
                            showError('Failed to retrieve stored information from database - ' +
                                error.message);
                        });
                    });
                }
                else {
                    loadDefaultRates();
                }
            }

            // Function: saveRates() - Save the currency exchange rates into DB
            function saveRates()
            {
                if (database) {
                    var elementUSD = document.getElementById('txtUSD');
                    var elementEUR = document.getElementById('txtEUR');
                    var elementAUS = document.getElementById('txtAUS');

                    database.transaction(function (tx) {
                        tx.executeSql("UPDATE " + DB_tableName + " SET key = 'USD',
                            value = ? WHERE id = 0", [elementUSD.value]);
                        tx.executeSql("UPDATE " + DB_tableName + " SET key = 'EUR',
                            value = ? WHERE id = 1", [elementEUR.value]);
                        tx.executeSql("UPDATE " + DB_tableName + " SET key = 'AUS',
                            value = ? WHERE id = 2", [elementAUS.value]);
                    });
                }
                loadRates();
            }

            // Function: deleteTable() - Delete currency exchange table from DB
            function deleteTable()
            {
                try {
                    if (window.openDatabase) {
                        database = openDatabase("ExchangeRatesDB", "1.0",
                                                "Exchange Rates Database");
                        if (database) {
                            database.transaction(function(tx) {
                                tx.executeSql("DROP TABLE " + DB_tableName, []);
                            });
                        }
                    }
                } catch(e) {
                }
            }

            // Function: loadDefaultRates() - Load the default exchange rates
            function loadDefaultRates()
            {
                var popUpElement = document.getElementById('popupConvertTo');
                var element = document.getElementById('txtUSD');
                element.value = "1.44";
                popUpElement.options[0].text = "USD";
                popUpElement.options[0].value = element.value;

                element = document.getElementById('txtEUR');
                element.value = "2.05";
                popUpElement.options[1].text = "EUR";
                popUpElement.options[1].value = element.value;

                element = document.getElementById('txtAUS');
                element.value = "1.19";
                popUpElement.options[2].text = "AUS";
                popUpElement.options[2].value = element.value;
            }


        The database code above is pretty straightforward - store the exchange rates inside the database and populate the pop-up menu part when the rates are retrieved.

        Modify the load() function as follows:

            //
            // Function: load()
            // Called by HTML body element's onload event when the Web application is ready to
            // start
            //
            function load()
            {
                dashcode.setupParts();

                initDB();   
                if (!database) {
                    loadDefaultRates();
                }
            }

        Press Command-r to test the application. When the application is loaded, the pop-up menu will now display the three different currencies (see Figure 17).

        Figure 17: The pop-up menu part displaying the different currencies

        When you tap on the Settings button, the exchange rates would also be displayed in the settings subview (see Figure 18).

        Figure 18: The exchange rates displayed in the settings subview


        Performing the Conversion
        You are now ready to perform the actual conversion of the currencies. In Dashcode, select the mainScreen subview and right-click on the Convert! Button and select Events'onclick (see Figure 19).

        Figure 19: Handling the onclick event for the Convert! button



        Name the event handler as btnConvert_ClickHandler and code it as follows:

            function btnConvert_ClickHandler(event)
            {
                var amount = document.getElementById("txtAmount").value;   
                var rates = document.getElementById("popupConvertTo").value;
                var result = amount * rates;
                alert(result);
            }

        Press Command-r to test the application. Enter an amount and select the currency to convert. Tapping on the Convert! button will now display the amount converted (see Figure 20).

        Figure 20: Try converting some currencies!


        Converting your Web Application into an iPhone Native Application
        Now that your application is completed, you may deploy your application onto a Web server so that users can access your application through the Safari browser on their iPhones. However, since this is a Web application, the user must have access to the Internet, or else there is no way to access your application. And since our application does not make use of any server-based data, it is a good candidate to convert into a native iPhone application. The easiest way would be to host the Web application within the Safari browser, which is represented by the WebView view in the iPhone SDK.

        In this section, I will show you how you can convert an iPhone Web application into a native iPhone application.

        First, deploy your Web application by clicking the Share item in Dashcode (see Figure 21). Click the Deploy button so that all the files of the application will be saved to a Web publishing directory. Take note of the Web publishing directory shown in Dashcode. It is saved in /Users//Sites/CurrencyConvertor/. You will make use of the files contained within this folder shortly.

        Figure 21: Deploying a Web application in Dashcode
        • Launch Xcode and create a new View-based Application project. Name the project as CurrencyConvertor.
        • In Finder, navigate to the /Users//Sites/CurrencyConvertor/ folder and select the files shown in Figure 22.
        Figure 22: All the project files created by Dashcode

        Drag-and-drop all the selected files onto the Resources folder in Xcode. Xcode will prompt you with a dialog (see Figure 23). Check the Copy items into destination group's folder (if needed) checkbox and click Add.


        Figure 23: Adding all the Dashcode files into the Resource folder in Xcode

        Perform a global Find-and-Replace (by pressing Shift-Command-F). Search and replace the following strings with an empty string (see Figure 24):

        Parts/
        Images/



        Figure 24: Replacing all instances of "Parts/" and "Images/" with an empty string

        This will update the various HTML and JavaScript files that reference other files using the Parts/ and Images/ folder. Files stored in the Resources folder of your Xcode application have no directory structure when they are deployed; hence all the files are in a flat directory.

        Select the files shown in Figure 25 and drag-and-drop them onto the Copy Bundle Resources (16) folder. This will ensure that all the HTML, JavaScript, CSS, and images files will be deployed together with your application.

        Figure 25: Copying all the Web files into the targets folder so that they are deployed together with your application


        In the CurrencyConvertorViewController.h file, add the following statements to define an outlet:

            #import

            @interface CurrencyConvertorViewController : UIViewController {
                IBOutlet UIWebView *webView;
            }

            @property (nonatomic, retain) UIWebView *webView;

            @end


        Double-click on the CurrencyConvertorViewController.xib file to open it in Interface Builder.
        Add a WebView view to the View window and control-click and drag the File's Owner item to the WebView view (see Figure 26). Select webView.


        Figure 26: Connecting an outlet to a view

        In the CurrencyConvertorViewController.m file, add the following statements:

            #import "CurrencyConvertorViewController.h"

            @implementation CurrencyConvertorViewController

            @synthesize webView;

            - (void)viewDidLoad {
                NSString *path = [[NSBundle mainBundle] pathForResource:@"index"
                                    ofType:@"html"];
                [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath: path
                                        isDirectory:NO] ]];
                [super viewDidLoad];
            }



        That's it! Press Command-r to test the application on the iPhone Simulator. The Web application is now hosted within the WebView view (see Figure 27). What you have just done is convert a Web application into a native application!

        Figure 27: Running the Web application as a native iPhone application