2012-09-18 52 views
4

我發現了幾個縮短URL的例子。但是他們都沒有爲我工作。如果有人有工作實例,請分享。 我都試過了,如何縮短目標中的URL C

NSString *apiEndpoint = [NSString stringWithFormat:@"http://tinyurl.com/api-create.php?url=%@",strUrl]; 
NSString *shortURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:apiEndpoint] 
               encoding:NSASCIIStringEncoding 
               error:nil]; 
NSLog(@"Long: %@ - Short: %@",strUrl,shortURL); 

NSString *shortenedURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://api.bit.ly/v3/shorten?login=%@&apikey=%@&longUrl=%@&format=txt", @"[email protected]", @"R_2db6e96aad348b8c993acf6ba80884c4", strUrl]] encoding:NSUTF8StringEncoding error:nil]; 

NSLog(@"Shoted url %@", [shortenedURL JSONValue]); 
+0

還第一粘貼此線以上我們的代碼strUrl = [strUrl stringByReplacingOccurrencesOfString:@ 「 」withString:@「」]; –

回答

4

只是儘量短網址波紋管代碼..

1.try第一這個..

NSString *urlstr = yourURL ;///here put your URL in string 
[urlstr retain]; 
NSString *apiEndpoint = [NSString stringWithFormat:@"http://ggl-shortener.appspot.com/?url=%@",urlstr]; 
[apiEndpoint retain]; 

NSLog(@"\n\n APIEndPoint : %@",apiEndpoint); 
NSString *shortURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:apiEndpoint] 
               encoding:NSASCIIStringEncoding 
               error:nil]; 
shortURL = [shortURL stringByReplacingOccurrencesOfString:@"{\"short_url\":\"" withString:@""]; 
shortURL = [shortURL stringByReplacingOccurrencesOfString:@"\",\"added_to_history\":false}" withString:@""]; 
[shortURL retain]; 
NSLog(@"Long: %@ - Short: %@",urlstr,shortURL); 

2.second方式是波紋管

NSString *urlstr =[yourURL stringByReplacingOccurrencesOfString:@" " withString:@""];///your url string 
      [urlstr retain]; 
      NSString *apiEndpoint = [NSString stringWithFormat:@"http://tinyurl.com/api-create.php?url=%@",urlstr]; 
      [apiEndpoint retain]; 

      NSLog(@"\n\n APIEndPoint : %@",apiEndpoint); 
      NSString *shortURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:apiEndpoint] 
                  encoding:NSASCIIStringEncoding 
                  error:nil]; 
[shortURL retain]; 
    NSLog(@"Long: %@ - Short: %@",urlstr,shortURL); 

希望這對你有所幫助...

:)

+0

感謝兄弟。但我仍然得到NULL的短url :(長:http://sandbox.saberion.com/beauty-morph/20120917-16380045-8658069 - 短:(null)............. ...你有什麼想法是什麼錯??? – sajaz

+1

嗨夥伴只是嘗試我的第二個選擇我知道你使用這個tinyurl,但嘗試我的代碼一次..希望這項工作很好...... :) –

+0

非常感謝。最後它的工作:) – sajaz

1

試試這個,它對我的​​工作很好。

NSString *apiEndpoint = [NSString stringWithFormat:@"http://tinyurl.com/api-create.php?url=%@",shareUrlString]; // The shareUrlString is NSString, which having URl 

shortenUrl = [NSString stringWithContentsOfURL:[NSURL URLWithString:apiEndpoint] encoding:NSASCIIStringEncoding error:nil]; //ShortenUrl is NSString