Last active
December 14, 2015 17:28
-
-
Save NicholasPeterson/5122244 to your computer and use it in GitHub Desktop.
NSUSL+bitly for easy synchronous url shortening (bit.ly SSL-API v3)
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
// 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 |
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
#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