Skip to content

Instantly share code, notes, and snippets.

@indragiek
Created May 2, 2011 03:26
Show Gist options
  • Save indragiek/951146 to your computer and use it in GitHub Desktop.
Save indragiek/951146 to your computer and use it in GitHub Desktop.
@interface NSString (Additions)
- (NSString*)stringByRemovingWhitespace;
@property (readonly) NSString *MD5;
@end
@implementation NSString (Additions)
- (NSString*)stringByRemovingWhitespace
{
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];
NSArray *parts = [self componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
return [filteredArray componentsJoinedByString:@" "];
}
// From <http://stackoverflow.com/questions/2018550/how-do-i-create-an-md5-hash-of-a-string-in-cocoa>
- (NSString*)MD5
{
const char *cStr = [self UTF8String];
unsigned char result[16];
CC_MD5( cStr, strlen(cStr), result );
return [[NSString stringWithFormat:
@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
] lowercaseString];
}
@end
static NSString* const kGravatarAPIRoot = @"http://www.gravatar.com/avatar/";
+ (NSImage*)avatarWithEmail:(NSString*)email size:(CGFloat)size defaultImage:(NSString*)def rating:(NSString*)rating error:(NSError**)error
{
if (!email) { return nil; }
NSMutableString *requestURL = [NSMutableString stringWithFormat:@"%@%@", kGravatarAPIRoot, [email stringByRemovingWhitespace].MD5];
if (size) { [requestURL appendFormat:@"?s=%d&", (int)size]; }
if (def) { [requestURL appendFormat:@"?d=%@&", def.URLEncodedString]; }
if (rating) { [requestURL appendFormat:@"?r=%@", rating]; }
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:requestURL]];
NSData *imageData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:error];
[request release];
return [[[NSImage alloc] initWithData:imageData] autorelease];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment