How to add Photos to the iPhone Simulator

Building an app that needs to access the photo library but don’t have any photos in the iPhone simulator? No problem. Follow these simple steps to import photos into the iPhone Simulator:

  1. Open the iPhone Simulator
  2. Browse to the photo you want to put into the simulator (Finder or web browser)
  3. Click and drag the photo over the simulator window. A green "plus" icon should appear under your cursor with the simulator frame highlighted. Drop the photo.
  4. Mobile Safari should open on the simulator to the location of the image you just dragged and dropped over it
  5. Note that if the image you dropped is linked in a webpage, it will open the link instead of the image URL.
  6. Click the mouse down over the image and hold it until a popup window appears.
  7. Click "Save Image"

The photo will now reside in the "Saved Photos" album on the iPhone Simulator. Rince and repeat as many times as you need to get all your photos in the album.

Easier Titanium XHR and AJAX Requests

One question I see a lot on the Appcelerator Titanium Developer Q&A is how to perform AJAX requests and/or work with APIs, etc. There is a built-in way to do this with the Ti.Network.HTTPClient module that is pretty easy, but it does have a few drawbacks and “gotchas”, like executing the “success” event for ANY returned status code – even 500 errors. Since working with APIs is so common with mobile apps, I made a wrapper function modeled after jQuery’s $.ajax method that I use in all my apps. It shortens the syntax quite a bit and is much more familiar to those who are used to using jQuery.

The usage looks like this:

// Geocode input text location
app.utils.ajax({
     url: 'http://maps.googleapis.com/maps/api/geocode/json?address=' + txtLocation.value +'&region=us&sensor=true',
     method: 'get',
     success: function(xhr) {
         var data = JSON.parse(xhr.responseText);
         Ti.API.info(data);

         if("OK" == data.status) {
             var res = data.results[0];
             if(res) {
                 alert("Location: " + res.geometry.location.lat + ', ' + res.geometry.location.lng);
             }
             // Do something with coordinates
         } else {
             Ti.UI.createAlertDialog({
                 title: 'Geocode Error',
                 message: 'Unable to geocode location input'
             }).show();
         }
     },
     error: function(xhr) {
         Ti.UI.createAlertDialog({
             title: 'Geocode Error',
             message: 'No location matches found. Please try something else.'
         }).show();
     }
});

And the actual code for the utility function:

/**  * Application Utilities and Helper Methods  **/
(function(_app) {
     _app.utils = {};

     // AJAX method that mimmicks jQuery's
     _app.utils.ajax = function(_props) {
          // Merge with default props
         var o = _app.combine({
             method: 'GET',
             url: null,
             data: false,
             contentType: 'application/json',

             // Ti API Options
             async: true,
             autoEncodeUrl: true,

             // Callbacks
             success: null,
             error: null,
             beforeSend: null,
             complete: null
         }, _props);

         Ti.API.info("XHR " + o.method + ": \n'" + o.url + "'...");
         var xhr = Ti.Network.createHTTPClient({
             autoEncodeUrl: o.autoEncodeUrl,
             async: o.async
         });

         // URL
         xhr.open(o.method, o.url);

         // Request header
         xhr.setRequestHeader('Content-Type', o.contentType);

         if(o.beforeSend) {
             o.beforeSend(xhr);
         }

         // Errors
         xhr.setTimeout(10000);
         xhr.onerror = function() {
             Ti.API.info('XHR "onerror" ['+this.status+']: '+this.responseText+'');
             if(null !== o.error) {
                 return o.error(this);
             }
         };

         // Success
         xhr.onload = function() {
             // Log
             Ti.API.info('XHR "onload" ['+this.status+']: '+this.responseText+'');

             // Success = 1xx or 2xx (3xx = redirect)
             if(this.status < 400) {
                 try {
                     if(null !== o.success) {
                         return o.success(this);
                     }
                 } catch(e) {
                     Ti.API.info('XHR success function threw Exception: ' + e + '');
                     return;
                 }

             // Error = 4xx or 5xx
             } else {
                 Ti.API.info('XHR error ['+this.status+']: '+this.responseText+'');
                 if(null !== o.error) {
                     return o.error(this);
                 }
             }
         };

         // Send
         if(o.data) {
             Ti.API.info(o.data);
             xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
             xhr.send(o.data);
         } else {
             xhr.send();
         }

         // Completed
         if(null !== o.complete) {
             return o.complete(this);
         }
     };

     // And it does depend on this code below to combine object properties:

     // Extend an object with the properties from another
     // (thanks Dojo - http://docs.dojocampus.org/dojo/mixin)
     var empty = {};
     function mixin(/*Object*/ target, /*Object*/ source){
         var name, s, i;
         for(name in source){
             s = source[name];
             if(!(name in target) || (target[name] !== s && (!(name in empty) || empty[name] !== s))){
                 target[name] = s;
             }
         }
         return target; // Object
     };
     _app.mixin = function(/*Object*/ obj, /*Object...*/ props){
         if(!obj){ obj = {}; }
         for(var i=1, l=arguments.length; i<l; i++){
             mixin(obj, arguments[i]);
         }         return obj; // Object
     };

     // Create a new object, combining the properties of the passed objects with the last arguments having
     // priority over the first ones
     _app.combine = function(/*Object*/ obj, /*Object...*/ props) {
         var newObj = {};
         for(var i=0, l=arguments.length; i<l; i++){
             mixin(newObj, arguments[i]);
         }
         return newObj;
     };
})(app);

The particular organization of this utilities file assumes that your app structure follows the organization model shown in the Tweetanium example app (using the ‘app’ namespace within a single window context), but is easy to adapt if you are not.

Count the Number of Object keys/properties in Node.js

When using the excellent formidable library to handle file uploads, I needed to get a count of the number of files unloaded in a multi-part form. Javascript arrays have a .length property that you can use, but objects do not. I instinctively typed:files.length

Which returned undefined. So if there is no length property present, an easy way to count the number of keys or properties of an object in ES5-compliant javascript environments like Node.js is to use the Object prototype directly:

Object.keys(files).length

A little more typing, but it is fast, efficient, and most importantly: already built-in.

Titanium Mobile: How to Display an Image with Pinch-to-Zoom and Panning

There are many things that are not immediately obvious when working with Appcelerator’s Titanium platform. Displaying a large image with support for common gestures like pinch-to-zoom or panning around, for instance. If you are used to the Titanium platform and developing apps with it, you think it would be available in the events you can listen for – something like "twofingertouch" or similar that would have a dictionary of coordinates for each finger that is present on the screen.

is one of the most often posted questions in the Q&A section.

Protected vs Private Scope: Arrogance, Fear, and Handcuffs

The age old private vs protected debate has been re-ignited in the PHP community recently following the decision of Doctrine2 and Symfony2 to make all class methods private until there is a very clear and proven reason to change them to protected or public. The intention is a good one – to ensure they are providing a clear and stable API through intentional and known extension points that they can better test and support. Fabien (the creator of Symfony) points to this benefit in an article of his own explaining the thinking behind the decision. The primary started point of Fabien’s article and the driving thought behind this whole change and philosophy is (emphasis his):

Having a few well defined extension points force the developer to extend your library the right way instead of hacking your code.

The problem is that this kind of thinking is a slippery slope that kills the spirit of programming. It alienates the more pragmatic developers within communities. Telling other developers that you are going to force them to work with your code in some pre-determined "right way" is an incredibly arrogant statement to make. more Instead of letting the codebase grow organically and be modified or extended at will, you handcuff developers and send them a different message. Allow me to re-phrase it using my own words:

I know the right way to use this code and I have thought of all the possible use cases. If you don’t agree, then you have to prove me wrong and wait until I either agree or figure out a better right way for you.

This is the real message developers hear when internal code is private scope or marked with the final keyword – a message that they have arbitrarily limited power and ability to make changes where they need to. But it doesn’t stop there.

When you take the position that all methods should be private unless proven otherwise, you plant a seed of fear in the developers that use your code. Fear that whenever they may have to veer off the beaten path to meet a project requirement they won’t be able to. Fear that they might miss deadlines waiting for the "right way"  to enable the functionality they need. Fear that they might have to modify or hack the actual file or class they need to change the behavior of to achieve the functionality they want within the project deadline because they are not able to extend it.

Using private scope removes the fun from programming and kills the hacking spirit by creating fear through the knowledge that you will not have the ability to make changes anywhere in the codebase you need to when you need to. You are no longer in control of your own code. You were forced to submit to a nanny state mentality by sacrificing your freedoms to modify the code for the promise of future stability and safety. That’s not a fun place to be when you’re on the receiving end, and it’s not a policy I would ever consider enforcing with my own code. I sincerely hope this line of thinking does not proliferate within the PHP community and infect other projects.

Listing Aliases Inside an Android Keystore File With Keytool

If you lose or forget your Android keystore file alias that is used to build APK files for distribution (like I did when trying to package Autoridge Lite for the Android Market), here is a quick and easy way to see them:

  1. Open a Terminal Window, Run This Command:

    keytool -list -keystore /location/of/your/com.example.keystore

    Make sure "keytool" is either in your PATH, or "cd" into the "tools" directory where your Android SDK files are.

  2. Enter your keystore password when prompted (you didn’t forget that too, did you? Did you?)
  3. See results! You should see something like the picture below if you did everything right. The alias is circled in yellow. If you have multiple aliases in your keystore, they will all be listed, one per line.

Continue reading

Zero to App in Two Weeks with Titanium

Like any web developer who has been sitting on the sidelines watching this mobile explosion happen in front of my eyes, I was eager to find a way to jump in. Up until about a month ago, I was still evaluating various different mobile development platforms – Titanium, PhoneGap, and Rhomobile, trying to decide which one I wanted to use to make my first mobile app. My only selection criteria was that the platform would have to be able to produce both iPhone and Android apps with the same code, because I wanted to be able to develop and release both an Android and iPhone apps without having to learn two completely different programming languages and development environments, and without having to do everything twice.
Continue reading

Practical Uses for PHP 5.3 Closures

Closures are a new language-level feature that has been added to php 5.3, along with namespaces, late static binding, and a slew of other new features, patches, and updates. If you’re like me, you might be wondering what the practical uses for these new features are before you can rightly justify diving in and using them in new or existing projects. I experimented a lot with closures and possible uses over the past few weeks, and came up with some compelling reasons to start using them.

Continue reading