原文出处:http://pelz-sherman.net/blog/2009/05/16/url-shortening-in-objective-c/
Here’s a little class I wrote this weekend to support URL shortening using the is.gd service.
I hope someone finds it useful.
// URLShortener.h
#import
@interface URLShortener : NSObject {}
+ (NSString *)shortURL:(NSString *)longURL;
@end
=================================
//
// URLShortener.m
// Creates a short URL from a long URL using the is.gd API.
/
#import "URLShortener.h"
@implementation URLShortener
+ (NSString *)shortURL:(NSString *)longURL {
NSURL *apiURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://is.gd/api.php?longurl=%@",longURL]];
NSError *error = nil;
NSString *result = [NSString stringWithContentsOfURL:apiURL encoding:NSISOLatin2StringEncoding error:&error];
if (error != nil) {
NSLog([error description]);
return nil;
} else {
return result;
}
}
@end
原文:http://uplink.to/home/support/uplink-to-web-service/url-shortening/
方法2:Shorten any URL over at uplink.to Calling http://uplink.to/uplinkto.php?longurl={escaped URL string} from any language will return the shortened URL in the http response. Here is an example in Cocoa:
-(NSString*)shortenURL:(NSString*)url {CFStringRef legalStr = CFSTR("!@#$%^&()<>?{},;'[]");NSString *escUrl = (NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)url, NULL, legalStr, kCFStringEncodingUTF8);NSString *apiEndpoint = [NSString stringWithFormat:@"http://uplink.to/uplinkto.php?longurl=%@",escUrl];NSError* error;NSString* shortURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:apiEndpoint]encoding:NSASCIIStringEncoding error:&error];if (shortURL)return shortURL;elsereturn [error localizedDescription]; }