iOS 5 Twitter SDK Available

October 13, 2011 14 comments

I could not find anyway online for testing if the user had the Twitter API available (IE: they’re running iOS 5). The best solution I came up with was to instantiate the TWTweetComposeViewController and check if it is nil. If so then I don’t include any references to Twitter in my app.

-(BOOL) twitterSDKIsAvailable{
    TWTweetComposeViewController *tweetViewController = [[TWTweetComposeViewController alloc] init];
    BOOL twitterSDKAvailable = tweetViewController != nil;
    if(tweetViewController != nil){
         [tweetViewController release];
    }

    return twitterSDKAvailable;
}

Adding state to NSURLConnection

July 8, 2011 2 comments

When you want to make a data request in Objective-C you typically use NSURLConnection and can either do it synchronously or asynchronously. Obviously the later is the preferred choice so you don’t lock out the thread. Unfortunately, you will run into the problem where you want to make concurrent requests and you’ll find it doesn’t work. This usually happens because you set your class as the delegate and if you kick off another request it’ll step on top of the previous one returning the wrong data. One way around this is to keep a NSMutableDictionary of NSMutableData objects using the NSURLConnection as the key. Unfortunately you can’t do this with NSURLConnection as it doesn’t have a unique identifier that you can use.

Unfortunately you can’t use categories for this since they only allow you to add in methods, and subclassing just to add a field is not the most elegant solution. Luckily for us Objective-C has something nifty called Associative References. Creating an associative reference will let you add data storage (AKA a new iVar) to an existing class without the need to sub-class it.

So enough jabbering, here’s an example:

DataProxy.h

#import <Foundation/Foundation.h>

@interface DataProxy : NSObject {
    NSMutableDictionary *dataStreams;
}

-(void) getData: (NSMutableArray*) arguments withDict: (NSMutableDictionary*) options;

-(NSString*) createUUID;

-(void) removeDataStream: (NSString*) uuid;
    
@property(nonatomic, retain) NSMutableDictionary *dataStreams;

@end

DataProxy.h

#import "DataProxy.h"
#import <objc/runtime.h>

@implementation DataProxy
@synthesize dataStreams;

static char dataInstanceKey;

-(void) getData: (NSMutableArray*) arguments withDict: (NSMutableDictionary*) options{
    if(dataStreams == nil){
        dataStreams = [[NSMutableDictionary alloc] init];
    }
    
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[options objectForKey:@"url"]]
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy 
                                     timeoutInterval:8.0];
    
    // The caller should set the UA
    [req setValue:[options objectForKey:@"ua"] forHTTPHeaderField:@"User-Agent"];
    
    // Create a UUID to associate with the request
    NSString *uuid = [self createUUID];
    
    // Create & store data keyed off of the UUID
    NSMutableDictionary *ds = [[NSMutableData alloc] initWithCapacity:2048];
    [dataStreams setObject:ds forKey:uuid];
    [ds release];
    
    // Create a URL connection
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    
    // Add an associative reference to the connection to keep the key for the data
    objc_setAssociatedObject(conn, &dataInstanceKey, uuid, OBJC_ASSOCIATION_RETAIN);
    
    // Kick off the connection
    [conn scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [conn start];
    [conn release];
}


#pragma mark -
#pragma mark Private

-(NSString*) createUUID{
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef str = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    
    return [(NSString*) str autorelease];
}

-(void) removeDataStream: (NSString*) uuid{
    NSMutableData *data = (NSMutableData*) [dataStreams objectForKey:uuid];
    if(data != nil){
        data = nil;
        [dataStreams removeObjectForKey:uuid];
    }
}


-(void) connection: (NSURLConnection *) theConnection didReceiveData: (NSData *) incrementalData{
    // Pull the key out of the connection (we add when the connection is instantiated)
    NSString *uuid = (NSString*) objc_getAssociatedObject(theConnection, &dataInstanceKey);
    
    // Add the data to the correct stream
    [[dataStreams objectForKey:uuid] appendData:incrementalData];
}

-(void) connectionDidFinishLoading: (NSURLConnection*) theConnection{
    // Pull the key out of the connection (we add when the connection is instantiated)
    NSString *uuid = (NSString*) objc_getAssociatedObject(theConnection, &dataInstanceKey);
    
    // Get the correct data
    NSMutableData *data = (NSMutableData*) [dataStreams objectForKey:uuid];
    
    // Convert the result into a string
    NSString *response = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

    // Do something with the response!    

    [response release];
    
    // Remove the data
    [self removeDataStream:uuid];
}

-(void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error{
    // Pull the key out of the connection (we add when the connection is instantiated)
    NSString *uuid = (NSString*) objc_getAssociatedObject(connection, &dataInstanceKey);
    
    // Do something with the error
    NSString *error = [error localizedDescription];

    // Remove the data
    [self removeDataStream:uuid];
}

#pragma mark -
#pragma mark Memory Management

- (void)dealloc {
    for(id data in dataStreams){
        if(data != nil){
            data = nil;
        }
    }    
    [dataStreams release], dataStreams = nil;
  
    [super dealloc];
}

@end

Fixing network printer issue on OSX 10.6.8

June 30, 2011 15 comments

The latest rollout of OSX 10.6.8 has an issue where it can no longer print to most network printers (over IP). To fix it you simply replace four files that cups uses and restart the service. Download the zip file below with the replacement files (from 10.6.6) and a shell script that will take care of everything for you.

http://zomgdinosaurs.com/printer_fix.zip

Thanks to http://blog.digitechhosting.com/?p=421 for the help.

Below is the script that does the heavy lifting for you:

#!/bin/bash  

echo "Fixing printers!"

echo "Checking your version of OSX"
ver=$(system_profiler SPSoftwareDataType | grep 'Mac OS X 10.6.8')
if [ -z "$ver" ]
then
  echo "You aren't running 10.6.8!"
  exit
fi

echo "You're running: $ver"
echo "Backing up files.."
mkdir ~/PrinterBackup
sudo cp /usr/libexec/cups/backend/dnssd ~/PrinterBackup/dnssd.bak
sudo cp /usr/libexec/cups/backend/lpd ~/PrinterBackup/lpd.bak
sudo cp /usr/libexec/cups/backend/ipp ~/PrinterBackup/ipp.bak
sudo cp /usr/libexec/cups/backend/socket ~/PrinterBackup/socket.bak

echo "Replacing 10.6.8 files with 10.6.6 files"
sudo cp dnssd /usr/libexec/cups/backend/dnssd
sudo cp lpd /usr/libexec/cups/backend/lpd
sudo cp ipp /usr/libexec/cups/backend/ipp
sudo cp socket /usr/libexec/cups/backend/socket

echo "Restarting cups"
sudo killall cupsd
sudo cupsd

echo "You should be good to go"

iOS Retina Sprites

May 11, 2011 7 comments

One of the great things about the iPhone 4 is the Retina Display. Native iOS apps make handling the switching between the non-retina and retina version of the image really easy. Simply supply the two files and suffix one with “@2x” and it handles the rest (ex: 1.png, 2@2x.png). Taking advantage of the retina display in a web app is not so easy, especially if you want to use sprites.

This example will assume that you have three images that you wish to turn into a sprite that will support both retina and non-retina displays.

Create Images

Retina images are basically twice the size of the non-retina version which is then rendered into the non-retina dimensions to double the DPI. This means that if you want a retina and non-retina version of an image you should start out with the retina version (lets say, 50px x 50px) and then generate your scaled down version at 50% (25px x 25px).

In our example we will have three images: a, b and c. These images are to be shown at 56px x 22px on the screen. This means that our retina version will need to be 112px x 44px and our non-retina version should be 56px x 22px. Once you have the retina and non-retina version of all three images (you should have six images total) you’ll want to create a zip file for the retina images and a zip file for the non-retina images.

Generate Sprites

There are a lot of useful services and tools that will generate your sprites for you. For this example we are going to be using the CSS Sprite Generator service at http://spritegen.website-performance.org/.

The settings between retina and non-retina are going to be slightly different so pay close attention to the different settings.

Generating Non-Retina Sprite:

  1. Select your zip file, be sure to pick the non-retina zip.
  2. Under “Sprite Output Options” > “Build Direction” choose “Horizontal”.
  3. Under “Sprite Output Options” > “Horizontal Offset” enter “25px”.
  4. Click “Create Sprite Image & CSS”

Save the outputted file as “test-sprite.png” and copy the generated CSS to a temporary file, we’ll come back to it momentarily.

Generating Retina Sprite:

  1. Select your zip file, be sure to pick the retina zip.
  2. Under “Sprite Output Options” > “Build Direction” choose “Horizontal”.
  3. Under “Sprite Output Options” > “Horizontal Offset” enter “50px”.
  4. Click “Create Sprite Image & CSS”

Save the outputted file as “test-sprite@2x.png”, you can ignore the CSS generated.

You probably notice that the only main difference between generating the retina and non-retina sprites was the horizontal offset. Basically we are going to have web kit scale our retina version by 50% so we want the offsets between the images in the sprite to remain the same. This means that the horizontal offset between the images will need to be doubled in the retina sprite, just like the images themselves.

Generate CSS/HTML

Unfortunately we aren’t so much generating CSS as we are piecing together some previously generated CSS.

Sample HTML

Here’s the HTML that we’re going to be styling:

<div class=”test-sprite” id=”a”></div>
<div class=”test-sprite” id=”b”></div>
<div class=”test-sprite” id=”c”></div>

Base CSS

Let’s define the test class which will be where we handle setting our default sprite properties (non-retina):

.test-sprite{
	background-image: url(images/test-sprite.png);
	width:56px;
	height:22px;
}

Take note of the width and height, it’s the size of the non-retina images. When we insert our retina version the browser will handle scaling them down to fit the correct dimensions. Now we need to specify our retina sprite, we do this via a CSS override of the previous class’ background image. The override is handling using CSS3 Media Selectors:

@media only screen and (-webkit-min-device-pixel-ratio: 1.5),
       only screen and (min--moz-device-pixel-ratio: 1.5),
       only screen and (min-resolution: 240dpi) {
		.test-sprite{
			background-image: url(images/test-sprite@2x.png);
			-moz-background-size: 218px 22px;
			-o-background-size: 218px 22px;
			-webkit-background-size: 218px 22px;
			background-size: 218px 22px;
		}
}

Here you can see we overrode the background image with our retina version as well as specified a background size. If you pay close attention you’ll notice that the dimensions do not match those of the image, but rather those of the non-retina image – this is where we utilize the browser to handle our retina scaling.

Sprites

Now its time to create our sprite classes, this is the easy part. You’ll need to reference the generated sprite CSS from the non-retina, it’s very important that you use the offsets provided by it rather then the retina version. All you care about is the background-position variable, the rest you’ll fill in yourself:

#a{ background-position: 0 50%; }
#b{ background-position: -81px 50% }
#c{ background-position: -162px 50% }

That was the easy part, just a simple background position offset with a 50% horizontal/vertical offset.

Uppercase Words in a JS String

April 7, 2011 2 comments

I ran into a problem today where our geo coder returns city names in all uppercase. Obviously this doesn’t look very good when you print it out to the screen so I wanted to make it pretty. A good example is Young America, MN. We get “YOUNG AMERICA”.. Here’s a quick way to clean it up using jQuery:

$.map("YOUNG AMERICA".split(" "), 
    function(s){ 
        return s.charAt(0).toUpperCase() + s.toLowerCase().slice(1); 
    }
).join(" ");

Explode the string into an array by splitting on the space, map that array into a function that returns the first character uppercased and the remaining characters in lower case. Then join the outputted array by a space.

This converts “young america” to “Young America”.

jQuery Mobile Slider Events

March 29, 2011 2 comments

Out of the box there is no way to ask a jQuery slider to notify you when the value changes. This was problematic for me on a mobile app as I needed to know as soon as the user toggled the component. Some googling didn’t turn up anything helpful and I was hesitant to add a custom trigger. Now don’t get me wrong, there were lots of examples dealing with the programatic interaction with sliders, but none where you weren’t the creator of the slider (in this case jQuery Mobile automagically does it).

After a little head scratching I realized that I could monitor the change event on the underlying select element that the slider was bound to. The only catch was to filter out change events that weren’t really changing the value.. The reason for this was because if you held your finder on the slider and drug it around the on state (example: half drag through the off side) the change event on the select element is continuously fired. Simply storing the previous state of the button did the trick.

Sample button HTML:

<div data-role="page" id="sample">
    <div data-role="header">
        <h1>Sample Page</h1>
    </div>
    <div data-role="content">    
        <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b">
            <li>Toggle Me <select name="slider" id="toggle-me" data-role="slider">
                <option value="off">Off</option>
                <option value="on">On</option>
            </select> 
            </li>
        </ul>
    </div>
</div>

JavaScript

var oldVal = $("#toggle-me").bind("change", function(){ 
    if(oldVal != $(this).val()){
        oldVal = $(this).val();
        console.log("val change to " + oldVal);
    }
 }).val()

Unable to access an error message corresponding to your field name

November 22, 2010 1 comment

If you use CodeIgniter and you have custom field validators you may have encountered this error before “Unable to access an error message corresponding to your field name”. I scratched my head for awhile on this one as I was calling $this->validation->set_message(…) in my validators. But oops, looks like I changed the function name and didn’t reflect it in the first parameter that set_message requires, which is the function name.

I don’t get why CI wants you to specify the function name when they can easily figure it out. Anyway, here is my new solution that will avoid this from happening ever again:

	function _duplicate_URL_check($URL){
		$this->load->model('Page_model');
	    $page = $this->Page_model->get_page_by_url($URL);      
	    
	    if(count($page) != 0){
	        $this->validation->set_message(__FUNCTION__, 'The URL you entered is already used.');
	        return FALSE;
	    }                
	    else{
	        return TRUE;
	    }
	}

All you have to do is replace “_duplicate_URL_check” with __FUNCTION__, which is PHP’s magic keyword for the current function’s name, and you’ll be good to go! 🙂

URL Validation in CodeIgniter

November 19, 2010 3 comments

CodeIgniter comes with a lot of great validators and libraries out of the box, but once place I’ve found it to be lacking is with URL validation. It has nice support for validating email addresses but almost nothing for URL checks. The only one that it provides is called prep_url which does nothing more then prepend “http://&#8221; to input text.

I wanted to be able to validate that the URL was properly formatted, things such as:

  • scheme
  • host
  • port
  • path
  • etc

However, there was nothing out of the box that handled this. I also wanted to validate that if the URL was properly formatted that the domain actually existed. So I built this out as well. To handle this you simple have to add a new library under application/libraries called MY_validation.php. This will allow you to extend the built-in validation library and add additional validators to it.

Then in your code, you can simply add additional validators like:

$rules['URL']  = 'required|trim|max_length[256]|xss_clean|prep_url|valid_url_format|url_exists|callback_duplicate_URL_check';

The two new validators are valid_url_format which checks for a properly formatted URL and url_exists which checks for a valid server. You should prefix the two with prep_url so that if they don’t enter a scheme the other validators won’t fail. The final validator, callback_duplicate_url_check is a custom validator for this controller that ensures the URL isn’t already loaded into the system.

So simply create ci/system/application/libraries/MY_validation.php and paste the following contents into it. Then be sure to load the validation library in your controller/method ($this->load->library(‘validation’);) and you should be good to go!

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Additional validations for URL testing.
 *
 * @package      Module Creator
 * @subpackage	ThirdParty
 * @category	Libraries
 * @author	Brian Antonelli <brian.antonelli@autotrader.com>
 * @created	11/19/2010
 */

class MY_validation extends CI_validation{
    
    function MY_validation(){
        parent::CI_validation();
    }                                
                        
    /**
	 * Validate URL format
	 *
	 * @access	public
	 * @param	string
	 * @return	string
	 */	
    function valid_url_format($str){
        $pattern = "|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i";
        if (!preg_match($pattern, $str)){
            $this->set_message('valid_url_format', 'The URL you entered is not correctly formatted.');
            return FALSE;
        }

        return TRUE;
    }       

	// --------------------------------------------------------------------
    

    /**
	 * Validates that a URL is accessible. Also takes ports into consideration. 
	 * Note: If you see "php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known" 
	 *          then you are having DNS resolution issues and need to fix Apache
	 *
	 * @access	public
	 * @param	string
	 * @return	string
	 */	
    function url_exists($url){                                   
        $url_data = parse_url($url); // scheme, host, port, path, query
        if(!fsockopen($url_data['host'], isset($url_data['port']) ? $url_data['port'] : 80)){
            $this->set_message('url_exists', 'The URL you entered is not accessible.');
            return FALSE;
        }               
        
        return TRUE;
    }  
}

Installing mod_pagespeed on RHEL

November 18, 2010 1 comment

mod_pagespeed was recently released by Google and is absolutely amazing. I recently installed it on RHEL and documented the process. The big issue I often run into is that I don’t have root access on my work machines so simply running an out of the box make doesn’t work for me. These instructions will go through the installation for a custom Apache directory.

This walkthrough assumes that you:

  • Apache will run under the devwww user
  • Have Apache2 installed to usr/sbin/httpd
  • Your home directory is /data/home/devwww
  • Have a custom Apache directory (/data/web) that contains:
    • httpd_confs directory for your httpd.conf file
    • modules directory for your custom modules
    • htdocs directory for your webserver root

First steps first, if you are lucky enough to have yum privileges you should install the base packages.

 
$ sudo yum install gcc-c++ make rpm-build

Next, install Chromium, this handles all of the necessary packages that mod_pagespeed will need

 
$ mkdir ~/bin
$ cd ~/bin
$ svn co http://src.chromium.org/svn/trunk/tools/depot_tools

Now edit your bash profile, you need to add Chromium to your path. Be sure to reload your shell afterwords.

 
$ vi ~/.bash_profile

Add to .bash_profile:

 
export HOME=/data/home/devwww
export PATH=$PATH:$HOME/bin/depot_tools

Next, make a directory to install mod_pagespeed from and then pull it down from the repo using gclient which you get from Chromium

 
$ cd /data
$ mkdir pagespeed
$ cd pagespeed
$ gclient config http://modpagespeed.googlecode.com/svn/tags/0.9.1.1/src
$ gclient sync --force

Once you’ve got all of the code checked out you’re ready to build:

 
$ cd /data/pagespeed/src
$ make BUILDTYPE=Release

After the build, you’ll want to make an installer. In this script you’ll customize all of your MAKE overrides, this is what gets you around the root access issues. Be sure to set your correct host name and port.

 
$ cd /data/pagespeed/src/install
$ touch rhel.sh
$ chmod +x rhel.sh
$ vi rhel.sh

rhel.sh:

 
#!/bin/sh

exec make \
    APACHE_USER=devwww \
    APACHE_DOC_ROOT=/data/web/htdocs \
    APACHE_ROOT=/usr/sbin/httpd \
    APACHE_MODULES=/data/web/modules \
    APACHE_CONF=/data/web/httpd_confs \
    MOD_PAGESPEED_FILE_ROOT=/data/mod_pagespeed \
    HOSTNAME=localhost:8000 \
    $*

Now you can run staging, and then install. If you want to verify the commands, add -n before the target (ex: ./rhel.sh -n staging)

 
$ ./rhel.sh staging
$ ./rhel.sh install

In your httpd_confs directory you’ll find pagespeed.conf. Copy the contents of that file into your httpd.conf file and you’ll be good to go!

One gotcha that I ran into was the location of mod_default. Since we tell MAKE that our module directory is /data/web/modules it will automatically add a LoadModule call for mod_deflate.so in that directory. Mine is actually located in /etc/httpd/modules/ with the rest of the out-of-the-box modules. I simply changed this and everything worked just fine.

Modify this module load in your httpd config:

 
LoadModule deflate_module /etc/httpd/modules/mod_deflate.so

Now fire up your server and go to http://localhost:8000/mod_pagespeed_example/index.html and you’ll be good to go!

BlackBerry PlayBook Hello World

October 29, 2010 Leave a comment

So the PB SDK comes with a Hello World application, its a bit more “complex” than your traditional Hello World as it allows for user input and has buttons and what not! Schnazzy! However, it’s just as much of a pain to get installed as it is getting the SDK and simulator up and running! It seems that Adobe has decided that if you don’t want to spend the money to buy FlashBuilder then they will make your life hell through some crazy command line hoops.

So simply extracting the HelloWorld.zip and installing it to the simulator is easier said then done. The biggest problem with this is that they don’t provide the compiled SWF — but they do at least provide the ActionScript source code! So after an hour of research I finally found a way to compile the SWF.

First things first, I’ll be referencing my own install directory so your mileage my vary. Again, this is all being done by the command line.

Extract the HelloWorld zip file

> cd /Users/bantonelli/Dev/blackberry-tablet-sdk-0.9.0/samples/projects
> unzip HelloWorld.zip
> cd HelloWorld/src

Now since we aren’t using FlashBuilder we need to go and modify the app configuration to point to the SWF that we’ll be compiling. Open up HelloWorld-app.xml in VI and go to line 48, set the value of <content> to HelloWorld.swf. Now go ahead and save and exit.

Now we can finally compile our AS file into the HelloWorld SWF. You would think, from all the AIR documentation out there that you would want to compile it via bin/mxmlc but you would be wrong! You’ll get all sorts of linker errors, especially related to the PB specific libs. I tried various ways of pointing it to the right libraries but alas it did not work. I dug around a bit more and found bin/amxmlc, aha! So now we can compile our SWF

> ../../../../bin/amxmlc HelloWorld.as
Loading configuration file /Users/bantonelli/Dev/blackberry-tablet-sdk-0.9.0/frameworks/air-config.xml
/Users/bantonelli/Dev/blackberry-tablet-sdk-0.9.0/samples/projects/HelloWorld/src/HelloWorld.swf (115327 bytes)

Now that we’re done with that we just have to call the AirPackager, point it to our config file, SWF file and any and all additional resources that our app uses (images, etc).. I think that’s a bit ridiculous! BTW, you’ll also have to point it to your VM’s current IP which I talked about in my previous post. Oh, and make sure the VM is running (something I forgot!).. Running the packager should make your BAR file, which you’ll need to visit after going through all of this..

> ../../../../bin/blackberry-airpackager -package HelloWorld.bar -installApp -launchApp HelloWorld-app.xml HelloWorld.swf hello.png -device 192.168.188.128

Using default icon: ../../../../bin/../samples/icons/blackberry-tablet-default-icon.png
The bar manifest file is valid.
Package created: HelloWorld.bar
Action: Install
File size: 129961
Installing ...
actual_dname::com.sample.HelloWorld.bXBsZS5IZWxsb1dvcmxkICAgICA
actual_id::bXBsZS5IZWxsb1dvcmxkICAgICA
actual_version::1.0.0.0
result::success
[-launchApp, -package, HelloWorld.bar, -device, 192.168.188.128]
Action: Launch
Launching com.sample.HelloWorld.bXBsZS5IZWxsb1dvcmxkICAgICA...
done

And you should be greeted with this nifty, fancy, fantabulous Hello World app!

That’s it!

Create your own website, free on WordPress.com.Create your own website.
Start free