2011-04-19 72 views
0

我想以编程方式将iPhone中的URl转换为TinyURL。这个怎么做?在iPhone中将URL转换为TinyURL

+0

你需要一些哈希函数,使字符串更小的工作。看到这个想法在C#可能会给你一个提示[见](http://stackoverflow.com/questions/1116860/whats-the-best-way-to-create-a-short-hash-similiar-to-what- tiny-url-does) – 2011-04-19 12:56:35

回答

5

微小的URL有一个简单的API,你可以使用,这是非常简单的

只需发送该请求与您的URL

http://tinyurl.com/api-create.php?url=http://yourURL.com/

它会返回一个很小的网址与你的链接

编辑:这里有一个工作示例,这是一个同步请求,但如果它需要太长时间,它可能会使您的应用程序无响应。

NSString *origUrl = @"http://stackoverflow.com"; 
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://tinyurl.com/api-create.php?url=%@", origUrl]]; 
NSURLRequest *request = [ NSURLRequest requestWithURL:url 
             cachePolicy:NSURLRequestReloadIgnoringCacheData 
            timeoutInterval:10.0 ]; 
NSError *error; 
NSURLResponse *response; 
NSData *myUrlData = [ NSURLConnection sendSynchronousRequest:request 
            returningResponse:&response 
               error:&error]; 
NSString *myTinyUrl = [[NSString alloc] initWithData:myUrlData encoding:NSUTF8StringEncoding]; 
//do stuff with url 
[myTinyUrl release]; 
+0

我喜欢你的答案,但是如果当时服务器停工或太忙请求呢?如果他完全依赖tinyUrl API,@Warrior应用程序将无法工作。 – 2011-04-19 13:01:13

+0

@AhmadTK:和你一样,我最初很长时间都在尝试Hector的链接,但现在它似乎很快就会响应,所以它很可能是暂时的故障。 – Tommy 2011-04-19 13:03:47

+0

嗯,我现在没有给出具体的代码示例,因为我是通过手机发布的。如果发生超时或其他错误,我会假设你的http请求会有一个回退 – Hector204 2011-04-19 13:03:50

0

比较容易的方式和ios7

NSError *error 
NSString *tinyURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://tinyurl.com/api-create.php?url=%@", YOUR-URL]] 
                encoding:NSASCIIStringEncoding error:&error]; 

// error handling here..