Chris Umbel

Basic Authentication with a NSURLRequest in Cocoa Touch

While working on a certain unnamed iPhone app lately I ran across the need to use basic authentication in communication with REST services. For something that seems to be such a fundamental need for mobile applications I figured most of the work would be done for me. Turns out that's not the case. A few details are left up to you, the Cocoa Touch programmer.

What Basic Authentication is

In order to implement basic authentication in Cocoa Touch it is important to understand how it works. Basic authentication tokens are essentially formatted into a string in the format:

username:password

They are then Base64-encoded and formatted into an "Authorization" HTTP header who's value looks like:

Basic c2NvdHQ6dGlnZXI=

where "c2NvdHQ6dGlnZXI=" is the encoded token pair and "Basic" is a hard-coded prependage.

Easy enough right? Encode username and password, slap it in the header and make the request.

What's not Provided by Cocoa Touch: Base64

I thought for sure I'd be able to leverage something out-of-the-box to handle the Base64 encoding. Surely I can do it by using some simple method or function somewhere. It'd just be a one-liner something-er-other, right? Right?? Wrong!

Nothing in Cocoa Touch natively provides you with Base64 encoding capabilities. You also don't have access to openssl on the iPhone via the SDK. In Cocoa Touch's defense I guess it never claimed to have the batteries included (my python & ruby soaked brain always expects everything to be done for me;)).

While I've seen suggestions to statically link openssl against your iPhone app it's not only overkill but presumably puts the responsibility on you to comply with U.S. export regulations (the cryptography in openssl is legally a munition in the states after all).

Besides, it's rather simple to implement Base64 yourself.

A Base64 Implementation

There are a number of implementations you can cherry-pick from elsewhere but in the spirit of demonstration I'll provide an example Base64 encoder that you can use in your project.

Contrary to the spirit of demonstration, however, I'm not going to explain it too much as it's not the subject of the post. If you need more background about the algorithm Ramkumar Menon wrote an excellent blog post about it. Also note that the code is arranged for readability, not conciseness, style or best-practices.

static char *alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

@implementation Base64
+(NSString *)encode:(NSData *)plainText {
	int encodedLength = (4 * (([plainText length] / 3) + (1 - (3 - ([plainText length] % 3)) / 3))) + 1;
	unsigned char *outputBuffer = malloc(encodedLength);
	unsigned char *inputBuffer = (unsigned char *)[plainText bytes];
	
	NSInteger i;
	NSInteger j = 0;
	int remain;
	
	for(i = 0; i < [plainText length]; i += 3) {
		remain = [plainText length] - i;
		
		outputBuffer[j++] = alphabet[(inputBuffer[i] & 0xFC) >> 2];
		outputBuffer[j++] = alphabet[((inputBuffer[i] & 0x03) << 4) | 
									 ((remain > 1) ? ((inputBuffer[i + 1] & 0xF0) >> 4): 0)];
		
		if(remain > 1)
			outputBuffer[j++] = alphabet[((inputBuffer[i + 1] & 0x0F) << 2)
										 | ((remain > 2) ? ((inputBuffer[i + 2] & 0xC0) >> 6) : 0)];
		else 
			outputBuffer[j++] = '=';
		
		if(remain > 2)
			outputBuffer[j++] = alphabet[inputBuffer[i + 2] & 0x3F];
		else
			outputBuffer[j++] = '=';			
	}
	
	outputBuffer[j] = 0;
	
	NSString *result = [NSString stringWithCString:outputBuffer length:strlen(outputBuffer)];
	free(outputBuffer);
	
	return result;
}
@end

Creating and Using a Proper Request

Now that we're ready to speak the encoding that the webservers are expecting we can get down to business. Consider the following code which executes an authenticated request against a resource via a synchronous NSURLRequest. Adding an "Authorization" header with the appropriately formatted, Base64-encoded authentication tokens are all that's required to authenticate the request.

NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/"];
NSString *userName = @"scott";
NSString *password = @"tiger";

NSError *myError = nil;

// create a plaintext string in the format username:password
NSMutableString *loginString = (NSMutableString*)[@"" stringByAppendingFormat:@"%@:%@", userName, password];

// employ the Base64 encoding above to encode the authentication tokens
NSString *encodedLoginData = [Base64 encode:[loginString dataUsingEncoding:NSUTF8StringEncoding]];
	
// create the contents of the header 
NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", encodedLoginData];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
    cachePolicy: NSURLRequestReloadIgnoringCacheData  
    timeoutInterval: 3];   

// add the header to the request.  Here's the $$$!!!
[request addValue:authHeader forHTTPHeaderField:@"Authorization"];

// perform the reqeust
NSURLResponse *response;

NSData *data = [NSURLConnection  
    sendSynchronousRequest: request  
    returningResponse: &response  
    error: &myError];  
*error = myError;

// POW, here's the content of the webserver's response.
NSString *result = [NSString stringWithCString:[data bytes] length:[data length]];

Conclusion

Aside from rolling-your-own (or snagging-someone-elses) Base64 implementation this isn't too bad.

To take it further you might employ NSURLCredential for storage of your authentication tokens.

Also if an asynchronous NSMutableURLRequest is used you can easily handle a webserver issuing a challenge by implementing the didReceiveAuthenticationChallenge message.

Sun Jan 24 2010 13:01:00 GMT+0000 (UTC)

Comments

Asynchronous Programming in Cocoa Touch

It's unavoidable. Pretty much anywhere you go as a programmer these days concurrency is important. It's no less important on mobile platforms like the iPhone. In this post I intend to outline the fundamental techniques necessary for asynchronous programming on the iPhone. While these techniques could very well apply to standard, desktop Cocoa I'll focus on Cocoa touch.

I'll cover three basic approaches: NSObject's performSelectorInBackground message, NSThread and NSTimer.

NSObject's performSelectorInBackground message

NSObject's performSelectorInBackground message can be used to easily farm off tasks that run asynchronously. Here's an example that could be placed in a view controller.

-(void) workerThread {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

	NSString *str = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.chrisumbel.com"]];

	[pool release];  
}

- (void)viewDidLoad {
    [super viewDidLoad];

	[self performSelectorInBackground:@selector(workerThread) withObject:nil];
}

performSelectorInBackground simply executed workerThread asynchronously. Not much to it.

Essentially that just loaded a string with the contents of a web page asynchronously in about the most raw form possible in Cocoa. Obviously this is far more simplistic than anything you'd do for production but it is a potentially long-running, I/O-bound operation which makes it a fine candidate for asynchronous execution. Note that it was unconcerned with synchronization and did not communicate back with the main thread.

Check out the the use of NSAutoreleasePool. It's imperative that you create an NSAutoreleasePool initially and release it before you exit the thread. It's responsible for memory management in the thread body.

NSThread

The most obvious class involved in asynchronous operations is NSThread which, as you would guess, effectively owns a separate thread of execution. Consider the following functional equivalent of the example above:

-(void)workerThread {
    // setup the thread's memory management.
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

    // grab the contents of a web page
    NSString *str = [NSString stringWithContentsOfURL:[NSURL
        URLWithString:@"http://www.chrisumbel.com"]];
	
    [pool release];  
}

-(void)viewDidLoad {
    [super viewDidLoad];

    // spawn a worker thread
    [NSThread detachNewThreadSelector:@selector(workerThread) 
	toTarget:self withObject:nil];
}

Thread Communication

Now I'll alter the example slightly to communicate back to the main thread. This is useful because you nearly always want to execute UI code on the main thread. The following example simply outputs its results to a label.

-(void)updateContent:(NSString *)content {
    [outputLabel setText:content];
}

-(void)workerThread {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

    NSString *str = [NSString stringWithContentsOfURL:
        [NSURL URLWithString:@"http://www.chrisumbel.com"]];
    
    // send our results back to the main thread
    [self performSelectorOnMainThread:@selector(updateContent:)
        withObject:str waitUntilDone:NO];
    
    [pool release];  
}

-(void)viewDidLoad {
    [super viewDidLoad];

    [NSThread detachNewThreadSelector:@selector(workerThread) 
	toTarget:self withObject:nil];
}

It's NSObject's performSelectorOnMainThread message that facilitates the inter-thread communication. Arguments to the target message (updateContent in my case) are passed along via withObject.

Synchronization

Mutex behavior is accomplished via the NSLock class. The following example synchronizes appending the results of the URL-lookup to a local file.

NSLock *myLock = nil;

-(void)workerThread:(NSString *)urlString {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

    NSString *str = [NSString stringWithContentsOfURL:
	[NSURL URLWithString:urlString]];

    // block other threads	    
    [myLock lock];
	
    FILE *f = fopen("content.txt", "a+");
    fputs([content UTF8String], f);
    fclose(f);
	
    // stop blocking
    [myLock unlock];

    [pool release];  
}

-(void)viewDidLoad {
    [super viewDidLoad];

    // create the lock object
    myLock = [[NSLock alloc] init];
	
    // spawn worker thread 1
    [NSThread detachNewThreadSelector:@selector(workerThread:) 
	toTarget:self withObject:@"http://www.apple.com"];
    
    // spawn worker thread 2
    [NSThread detachNewThreadSelector:@selector(workerThread:) 
	toTarget:self withObject:@"http://www.gnome.org"];
}

NSTimer

The NSThread examples above were true, honest-to-goodness multi-threaded where each task was running in a separate NSRunLoop (Cocoa event handling loop). By contrast the following code uses an NSTimer running on the main run-loop to periodically execute a timed operation. NSTimers aren't perfectly accurate, however. You shouldn't rely on them being real-time.

NSTimer *timer = nil;
NSInteger timesExecuted = 0;

-(void)timerTick {
    timesExecuted++;
    [outputLabel setText:[timesExecuted stringValue]];
}

-(void)viewDidLoad {
    [super viewDidLoad];

    // create a timer that ticks every 10 seconds and executes timerTick
    // which I defined above
    timer = [NSTimer scheduledTimerWithTimeInterval: 10.0 target:self 
	selector:@selector(timerTick) userInfo:nil repeats: YES];
}

Conclusion

Well, there's the basics. For more depth you can check out Apple's iPhone Threading Programming Guide It's quite comprehensive and definitely worth the read.

Sun Jan 17 2010 00:01:00 GMT+0000 (UTC)

Comments

NSXML-like XPath Support in Cocoa Touch with TouchXML

I haven't done any real, serious iPhone development until recently. Sure, I tooled around a bit and even had a few false starts on projects, but not much came out. What killed me was that I had no real *idea*. Without a concrete goal in mind it was especially hard to wade through a platform so different from those which I'm used to.

Well, that changed recently. I got an idea. Not a great one, but a good enough idea to keep me at my mac hacking something out. What's the idea? Well, I'm certainly not going to tell you yet! Besides, the actual app I'm writing isn't the focus of this post.

What is, however, is TouchXML which is, according to their website, "a lightweight replacement for Cocoa's NSXML cluster of classes". Why is that important? Because the iPhone SDK does not include NSXML which means no XPath.

Now, I don't know about you, but no XPath cramps my style! My style being cramped was another thing that caused me to have trouble focusing on the platform in the past.

Luckily, thanks to TouchXML it's about as easy as in standard Cocoa. I'll show you my typical example which gets a twitter user's status. Normally I reserve that for out-of-the-box libraries but I'm willing to make an exception here.

Assuming you've downloaded TouchXML, included it in your project like this tutorial describes and

 
#import "TouchXML.h"

then you can

 
/* create a url pointing to my status */
NSURL *url = [NSURL URLWithString: @"http://twitter.com/users/chrisumbel.xml"];
/* have TouchXML parse it into a CXMLDocument */
CXMLDocument *doc = [[[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil] autorelease];
/* execute some XPath which will return all status texts (will only be one) */
NSArray *resultNodes = [doc nodesForXPath:@"/user/status/text" error:nil];
 
NSString *status = @"";
/* pull the text element out, there should only be one so we'll just grab the first */
CXMLElement *resultElement = [resultNodes objectAtIndex:0];
/* pull the status string out  */
status = [resultElement stringValue];

and my twitter status is slapped into the status variable thusly.

So now that my style's not cramped and I have an idea I'm ready to code!

Sun Jan 03 2010 21:44:00 GMT+0000 (UTC)

Comments

Using Solr in Django for Full-Text Searching via Solango

Solr Logo I've been doing quite a bit of work with Solr lately, both at the office and at home and, by golly, I love it! It's very powerful and simple to integrate with regardless of your platform.

In this post I'll explain how to use Solr as a data-store independent search provider for Django projects. I'll assume that you have a functional Solr install and generally understand how to use it. If that's not the case Apache's Solr documentation can help.

Get Solango

The easiest way to get your project talking to Solr is via the Solango Django application. Grab the source from here and copy the solango sub-directory into your PYTHON_PATH.

Configure Solango

Solango must now be configured. Jump into the solango directory that you copied above and edit the settings.py file. Modify the SEARCH_UPDATE_URL, SEARCH_SELECT_URL, and SEARCH_PING_URLS settings to match your Solr environment. For example if your Solr instance was running locally on port 8080 your settings would look like:

SEARCH_UPDATE_URL = getattr(settings, "SEARCH_UPDATE_URL", "http://localhost:8080/solr/update")
SEARCH_SELECT_URL = getattr(settings, "SEARCH_SELECT_URL", "http://localhost:8080/solr/select")
SEARCH_PING_URLS =  getattr(settings, "SEARCH_PING_URLS", ["http://localhost:8080/solr/admin/ping",])

Configure Your Application

Solango configuration out of the way you can now configure your project's settings.py to include the solango app. For example:

INSTALLED_APPS = (
    'solango',
    # your other apps
)

Define the Model

Now I'll show you an example model that you could search upon. I'll create a standard model named Article and a Solr document type named ArticleDocument. Essentially ArticleDocuments are the Solr equivilent of Articles. The last line ties the model and the document together. Also note the copy setting for the document's fields. That instructs Solr to make them copy fields that target the default search field.

import solango

# regular model, lives relationally
class Article(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=1024)
    content = models.TextField()

# SearchDocument, lives in Solr
class ArticleDocument(solango.SearchDocument):
    title = solango.fields.CharField(copy=True)    
    content = solango.fields.TextField(copy=True)

# tie them together
solango.register(Article, ArticleDocument)

Define the Schema

With the meta data defined at the Django level we must now define it within Solr. Luckily solango simplifies this. Drop to a shell and run the following command in your project's main directory:

python manage.py solr --fields

This will output field definitions that you'll have to add to Solr's schema.xml.

########## FIELDS ###########

<field name="title" type="string" indexed="true" stored="true" omitNorms="false"
    required="false" multiValued="false"/>
<field name="content" type="string" indexed="true" stored="true" omitNorms="false"
    required="false" multiValued="false"/>
<field name="model" type="string" indexed="true" stored="true" omitNorms="false"
    required="true" multiValued="false"/>
<field name="id" type="string" indexed="true" stored="true" omitNorms="false"
    required="true" multiValued="false"/>

######## COPY FIELDS ########

<copyField source="title" dest="text"/>
<copyField source="content" dest="text"/>

Index

Assuming you have article data in your main data store it's simple to get it indexed with the following command. Keep in mind that I've had to specify nothing about connectivity to the relational data source above. Rather than use a data store specific Solr data import handler solango will use the Django model.

python manage.py solr --reindex 

Pow, let it run and your data is now indexed in Solr for speedy and powerful searching!

Search

Well, none of this would be useful unless it was actually searched, no? Below is an abbreviated view that queries Solr for ArticleDocuments. Thanks to duct-typing they can fit right in most places an Article model is used.

import solango

def search(search_string):
    articles = solango.connection.select(q = search_string).documents

That's just a basic search. More advanced features like facets and highlighting are supported as well. For details check out this documentation.

Conclusion

Well, it might not be as seamless as Ruby ActiveRecord's acts_as_solr, but solango certainly makes using Solr as a search provider for Django manageable. It decouples Solr from the data store. It provides manage.py-based management of Solr. It supports high level Solr features. It's not too shabby at all, no sir.

This post was but a brief introduction. The Django Solr Documentation can help complete the picture for you.

Fri Jan 01 2010 00:01:00 GMT+0000 (UTC)

Comments
< 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 >
Follow Chris
RSS Feed
Twitter
Facebook
CodePlex
github
LinkedIn
Google