Synchromation - Code

Signing Amazon CloudFront REST Requests

Whilst creating signed REST requests for Amazon S3 services can be a complicated affair as detailed here, signing for CloudFront is a far simpler and can be performed by a simple category on NSMutableURLRequest.

Call the method just before sending a synchronous (or indeed asynchronous) request.

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: cloudFrontURL];
[request signRequestForCloudFront];

Category...
@implementation NSMutableURLRequest (CloudFront)
- (void) signRequestForCloudFront
{
// Set Date header to date string in one of the RFC 2616 formats
// e.g. "Tue, 27 Mar 2007 21:06:08 +0000"
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat: @"EEE, d MMM yyyy HH:mm:ss zzzz"];
NSString *date = [dateFormatter stringFromDate:[NSDate date]];

[self addValue: date forHTTPHeaderField: @"Date"];

// For cloudfront the signature is calculated purely from the date sting only
NSString *signature = [self base64forData:[self HMACSHA1withKey: secretAccessKey forString: date]];

NSString *authorization = [NSString stringWithFormat:@"AWS %@:%@", accessKey, signature];

[self addValue: authorization forHTTPHeaderField: @"Authorization"];
}
€end

Please note this snippet requires a Base64 encoder and the SHA-1 hashing code from All-Seeing's asi-http-request on GitHub
Comments

Using Categories with UIColor

One way of globally caching frequently used UIColor values can be by using a category on UIColor.

This allows code such as..
aLabelView.textColor = [UIColor lightBeigeColor];

This is especially useful when optimising cellForRowAtIndexPath in a UITableView where all the subviews of the UITableViewCell being returned are being created programmatically for speed.

Example header file...
//  Add a category on to UIColor to add some of our own regularly used colours
#import <UIKit/UIKit.h>
@interface UIColor (UIColor_SDJColor)
+ (UIColor *) lightBeigeColor;
+ (UIColor *) darkBeigeColor;
@end

Example source file...
#import "UIColor+SDJColor.h"
@implementation UIColor (UIColor_SDJColor)
+ (UIColor *) lightBeigeColor;
{
static UIColor *lightBeige = nil;
// If we haven't already initialised the colour, then do it now
if (!lightBeige) {
lightBeige = [UIColor colorWithRed: 0.925f
green: 0.902f
blue: 0.835f
alpha: 1.000f];
[lightBeige retain];
}
return lightBeige;
}

+ (UIColor *) darkBeigeColor;
{
static UIColor *darkBeige = nil;
// If we haven't already initialised the colour, then do it now
if (!darkBeige) {
darkBeige = [UIColor colorWithRed: 0.875f
green: 0.839f
blue: 0.723f
alpha: 1.000f];
[darkBeige retain];
}
return darkBeige;
}
@end

This method can also be used to cache frequently used objects with other classes such as UIFont and UIImage where otherwise repeated calls could be expensive in terms of CPU time.
Comments