Smart PhonesAfter my last post, I had planned to write a series of how-to’s related to Titanium mobile app development. Alas, I’ve changed development modes again.

A brief history of my iPhone app development

I’m the first to admit that I was very late to the iPhone dev party. I bought a book at least a year ago and cracked it open. Then I realized it wasn’t going to be as easy as playing Lego Indiana Jones, so I took a little break.

When I got back to development, I decided to try out a couple of frameworks that I had been reading about online. The first was PhoneGap. It’s a cool framework that lets you build iPhone applications using Javascript, HTML and CSS. My first app was just a test — a few buttons, some pages and some basic animations. I was able to put it together very quickly and the result looked good in the iPhone simulator, but it was much too slow on my actual phone. I don’t think that’s necessarily a failure of PhoneGap — it’s simply that anything that’s running in the browser is slower than native code. And that’s what PhoneGap does. It wraps up your Javascript, HTML and CSS into a basic shell of an app and essentially lets mobile Safari do most of the work. That’s cool, but it just didn’t have the right feel, so I moved on.

The second framework I tried was Titanium. Titanium is similar to PhoneGap in the sense that the code is written in Javascript, HTML and CSS. It differs in how that code is ultimately converted to an iPhone app. In Titanium, the programming model mirrors the native (Objective C) model. The code is written in Javascript, but much of it is converted to Objective C and then compiled by Xcode. Some of the code is still passed on to mobile Safari, depending on how you set up your project and what types of views you use, but with Titanium, it is possible to create an app that uses native UIKit (the native iPhone) controls. So I built the app I described in my previous post. The app worked and it was snappy. All the buttons and animations worked as expected. Everything went well until I upgraded my phone to iOS 4.0 and updated XCode and the iPhone SDK.

After my upgrades, things just stopped working. Weird things … like my Edit button just stopped appearing on screen, though it was still appearing in the simulator. I upgraded Titanium and tried again, but had no luck.

What I’ve learned

First off, let me say that I think both PhoneGap and Titanium are very cool and that I really think having some options for developing iPhone apps is a worthy goal. I’ve learned that PhoneGap provides some native control options now. That would take care of my speed issues. Titanium is working for many developers, so clearly the problem is either in my code or my configuration.

However, what I learned was that the biggest portion of the learning curve for me was not so much the syntax of Objective C, but other things such as the development environment (Xcode and IB), the view and controller model of iPhone apps, and the massive amount of stuff in the iPhone SDK. It’s all a little overwhelming at first. Ironically, by using PhoneGap or Titanium, I wasn’t able to get completely away from all of these things.

The development environments

Titanium provides its own IDE of sorts. It’s a very simple interface. It definitely wins the overwhelming UI battle. PhoneGap doesn’t have an IDE. You use Xcode. No gain there. There’s always a learning curve for new software. Xcode and Interface Builder are no exceptions. Just dig in.

Development concepts

In my first job, I built TCP/IP applications in C on Sun and Cray machines. The first time I had to grok the fork/exec model and use signals to handle sockets, I thought my brain was going to explode. After that I took a job building a Windows application using Delphi 1. Handling memory paging to deal with the fact that our data was larger than the 16-bit systems would allow was the bane of my existence for a week or two. Next I converted that app to a ASP and COM+ application. That whole project was a constant nightmare of IUnknown that I’d rather forget. And the list goes on and on. After a while, and with a little perseverance all of those new concepts became old concepts as I understood them.

It’s the same with developing iPhone apps. Understanding views, windows, table views, navigation controllers, etc. is just about taking the time to dig in and learn. Ironically, to take advantage of the native controls in Titanium (and probably also in PhoneGap), you’ll have to learn the same concepts — just in a different language. In fact, by the time I finished my Titanium-based app, I had enough general concepts in my tool box that switching to native was surprisingly obvious. I just had to learn some new syntax.

Massive iPhone SDK

When iPhone SDK 4 released, Apple included this gem in the overview page: “a rich set of over 1500 new APIs”. Fifteen. Hundred. NEW. APIs. Yep, that means that there are a lot more than 1500 APIs in the SDK in general. Cool? Yes. Overwhelming? Definitely.

Here’s the thing, though. Using a framework like PhoneGap or Titanium limits your exposure to all those APIs. Is that good or bad? It’s good if you only need the APIs that are exposed. It’s bad if you need even one that’s not. I didn’t do a thorough review of which elements of the SDK are available under each framework, but most of the standard stuff is available: camera, gps, vibrate, sound, contacts, etc.

So the answer on this one is that you don’t have to learn as much stuff in PhoneGap or Titanium, but if your app needs something that’s not supported by the framework, you’re either going to have to build it into the framework (Titanium provides some instructions for this — not sure if PhoneGap allows it) or you’re going to switch to native. Either way, you’re going to have to know the native SDK to get there.

Last thoughts

Learning Objective C (what of it I know) has been an interesting challenge. I hoped it would be like C or C++. It’s a little like C. Syntactically it’s not like C++, but having a handle on OO from C++ has helped. I bought a good Objective C book to go along with my iPhone book and I’ve been really happy with both. I’m reading the Objective C book cover to cover. I’m a little more than half-way through and really glad I chose to read it. I’ve read most of the iPhone book, but I use it more as a reference for specific tasks.

Getting up the learning curve with the native development tools for the iPhone has been extremely rewarding. The apps that generated are quick and small and just feel right. I’m definitely going to stick with the native development tools. I think the other tools have a place and I applaud those who are developing them for their efforts to simplify iPhone app development. For me, though, the key was simply allowing myself to take the time to really get up to speed rather than trying to shortcut the development process with a third-party tool. Your mileage may vary … and I’d love to hear your thoughts.

{ Comments on this entry are closed }

Add a comment

I’ve been experimenting with Titanium for iPhone development recently. So far my experience has been a mix of frustrating and exciting. It’s amazing to actually deploy an app to my iPhone and have it do what I was expecting — that’s the exciting part. The frustrating part is a combination of the complexity of getting started with the tools, provisioning a phone, registering as a developer at Apple and finding meaningful documentation for the Titanium API.

So, in an effort to possibly help someone else get started with Titanium and also as a method for documenting my own successes, I’ve decided to develop some online articles and github repositories for all of this. Everything I share here is licensed under the Creative Commons Attribution-Share Alike 3.0 United States license, so grab the code and use it as a starting point if you want. If you redistribute the source, just include my attribution. If you compile it into the next killer app, don’t worry about the attribution.

The first thing I really wanted to build is a simple navigation system based on a list (or table) such that when a row is clicked, a new page flies in from the right. The new page should have the standard iPhone back button in the top-left corner to get back to the main page. A very simple video showing what I wanted (and eventually built) is available on YouTube here:

The great news is that Titanium supports several window and container classes that make this quite simple. Here is the code for the main window:

[-]?View Code JAVASCRIPT
/**
 * app.js - Main application entry point.
 *
 * @author Blake Schwendiman <blake.schwendiman@gmail.com>
 */
 
// include the data management object
Ti.include('/data.js');
 
/*
  create the first/main window. this is what will be seen when the application
  first launches
*/
var first = Ti.UI.createWindow({
  backgroundColor: "#fff",
  title: "Views"
});
 
/*
  get the data rows and add them to a table view, then add the table to
  the main window
*/
var rows = AppData.getData();
var table = Titanium.UI.createTableView({data: rows});
first.add(table);
 
/*
  Create a navigation group. This is the Titanium magic that makes
  all of the window navigation happen.
*/
var navGroup = Ti.UI.iPhone.createNavigationGroup({
	window: first
});
 
/*
  respond to taps/clicks on the table rows here. this function is the main
  dispatcher for the table rows. basically it sets an application property
  containing relevent information about which row was clicked, then creates
  an instance of the item window and opens that window.
*/
table.addEventListener('click', function(e) {
	var rowdata = e.rowData;
 
  if (rowdata) {
    var rowdata_string = JSON.stringify({title: rowdata.title, value: rowdata.value});
    Ti.App.Properties.setString('item_data', rowdata_string);
    var second = Titanium.UI.createWindow({
        url: '/item.js'
    });
    navGroup.open(second);
  }
});
 
/*
  Create a primary window for the application and add the navigation group to
  that window, then open it.
*/
var main = Ti.UI.createWindow();
main.add(navGroup);
main.open();

The first relevant section is the creation of the table (createTableView). It accepts a data parameter which is obtained in this application by calling AppData.getData(). I won’t go into great detail about that, but suffice it to say that the function returns a Javascript array of objects that looks something like this:

      return [{title: 'Row 1', hasChild: true, value: 'row-1'},
              {title: 'Row 2', hasChild: true, value: 'row-2'},
              {title: 'Row Delta', hasChild: true, value: 'Gamma'}];

The data should have at least a title for each row. The hasChild attribute displays the right-arrow indicator in the row. Many more attributes are available as documented here.

Simply by creating the table with the above data and adding it to the main window, Titanium generates a standard iPhone table view as shown in the video as the primary window. The addEventListener call about half-way through the code is the main functional core of the application. This event handler responds to clicks/taps on the table rows. The code uses the passed event object to look up the data associated with the row and set it into the application properties object as described in this article about persisting objects in Titanium. This is done because the next step in the event handler creates a new window and opens it.

Here’s the cool part: By adding the new secondary window to the same navigation group as the primary window, Titanium manages the creation of the back button in the top-left corner of the secondary window. The back button automatically gets the title of the main window and automatically responds to the click/tap event. You don’t have to do anything more.

I haven’t included the source of the secondary window in this article because it doesn’t do much. However, you can download the entire source of this project from github: Ti-Demo-iPhone-Table-Views.

This article and app is intended to be a basic reusable starting point for applications that use a list or table as their primary navigation. Some of my favorite apps that use this model are:

{ Comments on this entry are closed }

Add a comment

Thesis 1.6 User Customization Guide

by admin on February 9, 2010

book1-e1264776924783As an avid fan of the Thesis theme for Wordpress, I thought I’d pass on a little news about a new eBook specifically focused on Thesis theme customizations. If you’re just getting started with Thesis or if you’re considering the theme but haven’t decided if you need it yet, check out this guide: Thesis 1.6 User Customization Guide.

Honestly the guide isn’t the prettiest eBook I’ve ever seen, but it really is packed with information. You’ll want to read it online as it links to YouTube for video tutorials and other online resources.

{ Comments on this entry are closed }

Add a comment

Desert Code Camp

by admin on November 6, 2009

Here, finally is the post for Desert Code Camp that I promised to make available. First off, thanks to everyone who attended my session on Integrating Facebook Connect. Secondly, please feel free to ask me questions via email, Twitter, or by commenting here.

Please feel free to download the source code. For each file in the source archive, there is an initial file and a final file. The final version of each file is the more interesting one with the FB code integrated.

In the code you’ll find usage samples for the following:

  • FB.ensureInit
  • FB.Connect.requireSession
  • FB.Connect.forceSessionRefresh
  • FB.Connect.logout
  • FB.init
  • FB_RequireFeatures
  • fb:profile-pic
  • fb:name
  • FB.Facebook.apiClient.friends_get
  • FB.XFBML.Host.parseDomTree
  • FB.Facebook.apiClient.users_getInfo
  • fb:live-stream

The demo site is still live at http://xfcg.com/fbp. For example, the page in the source archive called event-final.html is at http://xfcg.com/fbp/event-final.html.

Here are the basic steps for setting up a new Facebook Connect application:

  1. Install the Facebook Developer Application on your Facebook profile
  2. Create a new application
  3. Upload the xd_receiver file
  4. Add the FB xmlns attribute to your html tag
  5. Add the Facebook JS file
  6. Call init in your page

More information about Facebook Connect Integration is available from these other posts:

Again, please comment or message me if I’ve missed something important or if I didn’t answer your specific question. I’d love to be able to help.

{ Comments on this entry are closed }

Add a comment

Choose better passwords

by admin on September 29, 2009

A friend of mine recently fell victim to the Facebook 419 scam (basically someone logs into your Facebook account and asks your friends for money).

There are lots of ways bad things can happen to your computer and your online accounts, but if you use weak passwords, you’re increasing the risk that something bad will eventually happen to you. There are lots of articles about what makes a strong password, but I want to tell you how to create a strong password that’s easy for you to remember. If you have to write down your strong passwords, then you probably haven’t accomplished much.

If you read the Wikipedia article above, you’ll see that one recommendation is that passwords should be 12-14 characters long. If you’re like most of us, creating a password of that length that includes numbers, letters and special characters can seem daunting. Let me share some tricks I’ve learned in the past decade or so that I’ve been working online.

First of all, passwords containing any part of your birthday or anniversary are usually a bad idea. Especially if that information is displayed in your account online (Facebook). Also passwords that contain your spouse’s name, your kids names, etc. aren’t going to be too tricky in this world of social networking.

So, what do you choose? My favorite method right now is using songs, poems or other text you have memorized in the course of your lifetime to create a long, but easy-to-remember password.

Here’s how it works.

  1. Choose your text. For the example, I’m going to use the first line of the Gettysburg address, “Four score and seven years ago our fathers brought forth, upon this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.”
  2. Now reduce this to just the first 14 words as such: “Four score and seven years ago our fathers brought forth, upon this continent”
  3. Now just use the first letter of each word with proper capitalization and punctuation and you suddenly have a very good password: ‘Fsasyaofbf,utc’.

Notice that the password contains uppercase and lowercase letters and one special character, a comma. Yes, keep the comma in the password. You could also substitute the actual numbers into the text as such: ‘4sa7yaofbf,utc’. Now the password contains numbers, letters and special characters. If you just look at the password it appears completely random, but it’s so easy to remember.

The same thing applies to songs. Perhaps you’re a fan of Sean Kingston, so you choose the chorus of “Fire Burning” which is “Somebody call 911 Shawty fire burning on the dance floor…” Your new password is ‘Sc911Sfbotdf’.

If you’re a Bible reader, you have many, many ways to create complex passwords. For example you may include the scriptural reference in addition to a portion of the referenced passage. You might choose John 3:16, “For God so loved the world, that he gave his only begotten Son…” to create the password, ‘J3:16FGsltw,thghobS’. That one is 19 characters long, contains uppercase and lowercase letters, numbers and two special characters, but it’s amazingly simple to remember.

Using this technique, you can also create a set of strong passwords that you can use on different sites. Perhaps you associate the first letter of the site name with an author, scripture or recording artist/song. Twitter then becomes related to Thoreau or Thessalonians or Til Tuesday, while Facebook is related to Faulkner or First Timothy or Fatboy Slim.

My best recommendation is to start right away with at least one strong password. Get rid of your 4-6 character passwords. Get rid of your birthday or name-based passwords. Pick something that you’ve already memorized and make a password that really works.

Last note: Unfortunately not all web sites allow you to be completely creative with your passwords. Some sites don’t allow special characters. Other’s set limits on the length of a password. Hopefully that will change soon, but until then, you might have to tweak some of your choice to fit some of the sites you use. Don’t let that discourage you from using better passwords on the sites that allow it.

{ Comments on this entry are closed }

Add a comment

Signing AWS requests in PHP

by admin on August 19, 2009

Recently Amazon added the requirement that all requests must be signed. The process of signing requests is documented on this product advertising API page. Based on the steps listed there, and with a lot of help from @giltotherescue, I was able to create a PHP function to create a signed request URI based on a simple set of request parameters.

function makeAWSUrl($parameters, $associate_tag, $access_key, $secret_key, $aws_version = '2009-06-01') {
  $host = 'ecs.amazonaws.com';
  $path = '/onca/xml';
 
  $query = array(        
    'Service' => 'AWSECommerceService',
    'AWSAccessKeyId' => $access_key,
    'AssociateTag' => $associate_tag,
    'Timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
    'Version' => $aws_version,
  );
 
  // Merge in any options that were passed in
  if (is_array($parameters)) {
    $query = array_merge($query, $parameters);
   }
 
  // Do a case-insensitive, natural order sort on the array keys.
  ksort($query);
 
  // create the signable string
  $temp = array();
  foreach ($query as $k => $v) {
    $temp[] = str_replace('%7E', '~', rawurlencode($k)) . '=' . str_replace('%7E', '~', rawurlencode($v));
  }
  $signable = implode('&', $temp);
 
  $stringToSign = "GET\n$host\n$path\n$signable";
 
  // Hash the AWS secret key and generate a signature for the request.
  $hex_str = hash_hmac('sha256', $stringToSign, $secret_key);
  $raw = '';
  for ($i = 0; $i < strlen($hex_str); $i += 2) {
    $raw .= chr(hexdec(substr($hex_str, $i, 2)));
  }
 
  $query['Signature'] = base64_encode($raw);
  ksort($query);
 
  $temp = array();
  foreach ($query as $k => $v) {
    $temp[] = rawurlencode($k) . '=' . rawurlencode($v);
  }
  $final = implode('&', $temp);
 
  return 'http://' . $host . $path . '?' . $final;
}

Using the function is simple. The first parameter is a PHP array of AWS parameters, the others are standard associate tags and keys. Here’s an example:

$url = makeAWSUrl(array('Keywords' => 'Jaco Pastorius',                           
                      'Operation' => 'ItemSearch',                          
                      'ResponseGroup' => 'Medium',                           
                      'SearchIndex' => 'Music',                           
                      'salesrank' => 'Bestselling'),  
  'YOUR_ASSOC_TAG', 'YOUR_ACCESS_KEY', 'YOUR_SECRET_KEY');

The result of the above call (using my tags and keys) is:

http://ecs.amazonaws.com/onca/xml?AWSAccessKeyId=[MYKEY]&AssociateTag=blakesblogand-20&Keywords=Jaco%20Pastorius&Operation=ItemSearch&ResponseGroup=Medium&SearchIndex=Music&Service=AWSECommerceService&Signature=qZ%2BheDqfZi79b2Xg0JSP2kgG2FgQn823GLn0m1sVmnM%3D&Timestamp=2009-08-19T22%3A53%3A29Z&Version=2009-06-01&salesrank=Bestselling

As always, give me some feedback, take the code and make it better. Share it and include it in your libraries … have fun!

{ Comments on this entry are closed }

Add a comment

SCP for Komodo IDE

by admin on August 17, 2009

I have just finished developing my first Komodo IDE plugin. I love Komodo. It’s the first IDE for PHP that I’ve been very, very happy using. I’ve run it on Windows, Linux and now on a MacBook. The only frustration I’ve had is that Komodo doesn’t support basic integrated file uploading via SCP. While it is possible to save a file remotely, there is no simple way to save a file locally and upload it to a mapped location on a remote server from within the IDE.

Fortunately Komodo also provides a simple method for creating extensions within the IDE itself, so I gave it a try. Within a few hours I was able to build an extension to do exactly what I needed and configure it on a per-project basis. I’ve made the extension available as an MIT-licensed, open-source project. As always, this project is included on the open source tools page.

{ Comments on this entry are closed }

Add a comment

My article Integrating Facebook Connect using the Thesis theme has generated a great deal of interest and several requests for a WordPress plugin. I personally haven’t had the time or inclination to create a plugin, but my friend and colleague Aaron Collegeman has. He was interested in the concept for one of his projects and asked permission to use my code.

Yesterday he released the plugin as an open source project. I haven’t had a chance to install the plugin, but having worked with Aaron in the past, I’m sure it’s top notch. I looked at the source code and really like the way he developed the integration with WordPress.

If you’re interested in adding Facebook comments to your WordPress blog, I suggest you give Aaron’s plugin a try. I’ve included this plugin on my open source tools page.

{ Comments on this entry are closed }

Add a comment

Doing more at once

by admin on June 17, 2009

I’ve been doing a lot of work with curl_multi in PHP lately because it just makes sense to do as much work in parallel as possible (in most cases). I’ll be writing up my experiences with curl_multi later.

So, yesterday’s announcement by the Facebook development team about fql.multiquery couldn’t have come at a better time for me. Experienced web developers (and multi-tiered application developers in general) have all learned that performing work in the proper tier is always the most efficient way to work. Data should be managed in the database tier and as separately from the application tier as possible. This announcement from the Facebook development team is great news for Facebook application developers everywhere. Kudos to them!

{ Comments on this entry are closed }

Add a comment

Another way to cache

by admin on June 11, 2009

Obviously, I’m a big fan of the performance increases that can be achieved by using memcache. Another potential cache-based tool for enhancing your server-side PHP code is to use an opcode compiler and caching tool such as APC.

apc-stats-graphIn addition to being a fantastic piece of technology by itself, APC also provides meaningful tuning options and detailed statistics. The screen shot here shows just a fraction of the information collected by APC.

So far, my experience with APC has been very positive, but don’t take my word for it. Check out some of the performance results: here, here and here.

As always, tuning to a particular application or server is critical. Be sure to read the manual!

{ Comments on this entry are closed }

Add a comment