Skip to content

Instantly share code, notes, and snippets.

@NicholasPeterson
Last active December 14, 2015 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NicholasPeterson/5122244 to your computer and use it in GitHub Desktop.
Save NicholasPeterson/5122244 to your computer and use it in GitHub Desktop.
NSUSL+bitly for easy synchronous url shortening (bit.ly SSL-API v3)
// Requires SBJSON, Uses my own percent escapeing, But cocoas will do for this task.
// All methods return nil on errors.
@interface NSURL (Bitly)
// Easy NSURL
+ (NSURL *) shortUrlWithString:(NSString *)string;
// Easy URL String
+ (NSString *)shortAbsoluteURLStringWithString:(NSString *)string;
// Returns full bitly response
+ (NSDictionary *)requestShortURLWithString:(NSString *)string
@end
#import "NSURL+Bitly.h"
#define kBitlyAccessToken @"ACCESS_TOKEN"
#define kBitlyFormat @"https://api-ssl.bitly.com/v3/shorten/?access_token=%@&longUrl=%@&format=json"
@implementation NSURL (Bitly)
+ (NSURL *)shortURLWithString:(NSString *)string
{
NSString *urlString = [NSURL shortAbsoluteURLStringWithString:string];
if (urlString) {
return nil;
}
return [NSURL URLWithString:urlString];
}
+ (NSString *)shortAbsoluteURLStringWithString:(NSString *)string
{
NSDictionary *info = [NSURL requestShortURLWithString:string];
if ([[info objectForKey:@"status_code"] integerValue] != 200) {
NSLog(@"Could not shorten url: %@", info);
return nil;
}
NSString *urlString = [[info objectForKey:@"data"] objectForKey:@"url"];
if (![urlString length]) {
NSLog(@"Could not shorten url: No url found");
return nil;
}
return urlString;
}
+ (NSDictionary *)requestShortURLWithString:(NSString *)string
{
NSString *versionCheckURL = [NSString stringWithFormat:kBitlyFormat, kBitlyAccessToken, [string percentEscapeString]];
NSURL *url = [NSURL URLWithString:versionCheckURL];
NSError *loadError = nil;
NSString *htmlData = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&loadError];
if (!htmlData) {
return nil;
}
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *bitlyInfo = [parser objectWithString:htmlData error:nil];
[parser release];
return bitlyInfo;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment