Created
May 2, 2011 03:26
-
-
Save indragiek/951146 to your computer and use it in GitHub Desktop.
Using the Gravatar API in a Cocoa Application: http://blog.indragie.com/post/5122436268/using-the-gravatar-api-in-a-cocoa-application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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