简体   繁体   English

iOS开发:如何缩短代码中的URL?

[英]iOS Development: How can I shorten a URL from my code?

I'm building an iPhone app and I'd like to include functionality that allows users to login to twitter and tweet a link to my app. 我正在构建一个iPhone应用程序,我希望包含允许用户登录到Twitter并发布指向我的应用程序的链接的功能。 In order to do this, however, the tweet will need to shorten the URL to my app on the App Store. 但是,为了做到这一点,推文需要缩短我在App Store上的应用程序的URL。 How can I write code to shorten a URL for a tweet? 如何编写代码来缩短推文的URL?

I've done a search for this and found a tutorial on iCodeBlog , as well as some questions posted on SO , however, they're all either more work than I think is needed or they're using http://api.tr.im , which is no longer available. 我已经对此进行了搜索并找到了关于iCodeBlog的教程 ,以及在SO上发布的一些问题 ,但是,它们都比我认为需要的更多工作或者他们正在使用http://api.tr .im ,已不再可用。 I'm hoping there's a newer approach to this that is as simple as the iCodeBlog solution. 我希望有一个更新的方法,就像iCodeBlog解决方案一样简单。

Thanks for your wisdom! 谢谢你的智慧!

I just google a few minutes because I'm also interested in that topic. 我只是谷歌几分钟,因为我也对这个话题感兴趣。 And I found this: TinyURL API I think that's the easiest way to implement something like this. 我发现了这个: TinyURL API我认为这是实现这样的最简单方法。 I think I'll write a little class for this to use it in further projects. 我想我会为此写一个小课程,以便在进一步的项目中使用它。 :-D :-D

Thanks to Sandro and woodleader: 感谢Sandro和woodleader:

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

You simple do a HTTP Request to an Service of your choice. 您可以简单地对您选择的服务执行HTTP请求。 I have choosen l.pr in this example. 我在这个例子中选择了l.pr。 Many other Services have such an easy API. 许多其他服务都有这么简单的API。 The magic here is in a method that is a part of NSString. 这里的神奇之处在于一个NSString的一部分方法。 This method is called stringWithContentsOfURL. 此方法称为stringWithContentsOfURL。 It will easily allow you to grab the text of any remote source. 它将很容易让您获取任何远程源的文本。

As an example: 举个例子:

NSString *url    = @"http://woodleader.org";
NSString *apiEndpoint = [NSString stringWithFormat:@"http:/api.l.pr/shorten?apikey=axbymc46859i685jfk9fk&longurl=%@",url];
NSString *shortURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:apiEndpoint]
         encoding:NSASCIIStringEncoding
         error:nil];
NSLog(@"Long: %@ - Short: %@",url,shortURL);

Here's a blog post on how to shorten a url using bit.ly 这是一篇关于如何使用bit.ly缩短网址的博客文章

http://www.aproposmac.com/2012/01/shorten-url-using-bitly-in-objective-c.html http://www.aproposmac.com/2012/01/shorten-url-using-bitly-in-objective-c.html

Very Simple.. 非常简单..

Try this sample.. Its working well for me. 试试这个样本..它适合我。

Sample: URL Shortner in ios programatically 示例: 以编程方式使用ios中的URL Shortner

(Or) (要么)

Http Post Method via google api: http://www.warewoof.com/goo-gl-url-shortener-in-ios/ Http Post方法通过google api: http //www.warewoof.com/goo-gl-url-shortener-in-ios/

If you decided to use Google Shortener API, then this can be an answer. 如果您决定使用Google Shortener API,那么可以是一个答案。 They use AFNetworking, written in Swift to get URL shortened. 他们使用用Swift编写的AFNetworking来缩短URL。 The sample code as following: 示例代码如下:

func getShorURLFromGoogle(longURL: String) {
    let manager = AFHTTPRequestOperationManager()
    manager.requestSerializer = AFJSONRequestSerializer() as AFJSONRequestSerializer
    let params = [
        "longUrl": longURL
    ]
    let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    manager.POST("https://www.googleapis.com/urlshortener/v1/url?key=\(appDelegate.googleMapsApiKey)", parameters: params, success: {
        (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
        if let responseObject = responseObject as? NSDictionary {
            //println(responseObject["id"] as String)
            self.shortURL = responseObject["id"] as? String //That's what you want  
        }
        },
        failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
            println("Error while requesting shortened: " + error.localizedDescription)
    })
} 

I use the below code. 我使用下面的代码。

    #define BITLY_LOGIN     @"pooja12"
    #define BITLY_APIKEY    @"R_c7045505f04343a7833721225740215c"
- (NSString *) shortURL {
        NSString *uri = [self absoluteString];
            NSString *fmt = [NSString stringWithFormat: @"http://api.bitly.com/v3/shorten?login=%@&apiKey=%@&longUrl=%@&format=txt", BITLY_LOGIN, BITLY_APIKEY, uri];
            NSURL *requestUrl = [NSURL URLWithString: fmt];
            //NSString *shortUri = [NSString stringWithContentsOfURL: requestUrl];
            //NSString *shortUri = [NSString stringWithContentsOfURL: requestUrl];
            NSError *error = nil;
            NSString *shortUri = [NSString stringWithContentsOfURL:requestUrl encoding:NSUTF8StringEncoding error:&error];
            shortUri = [shortUri stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
// here i call the above methods

      NSURL *shareUrl = [NSURL URLWithString:@"-url-"];
      NSString *shortenStr = [shareUrl shortURL];
      NSLog(@"Short url is %@", shortenStr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 iOS开发:如何从模式视图返回数据? - iOS Development: How can I return data from a modal view? 如何检查我的iOS应用程序是否由用户审核和评级,或者不是我的代码 - How can I check that my iOS app is reviewed & rated by a user or not from my code iOS开发:如何加强核心数据的内存使用量? - iOS Development: How can I tighten up my Core Data memory usage? iOS开发:如何使视图向右过渡而不是默认向左过渡? - iOS Development: How can I make my view transition to the right instead of to the default left? iOS 开发:如何对我的应用程序进行更改以使其仅影响新用户? - iOS Development: How can I make changes to my app so that it only affects new users? 如何在iOS中改进我的TWTweetComposeViewController代码? - How can I improve my TWTweetComposeViewController code in iOS? iOS开发:如何防止iPad在iPad模式下运行通用应用程序? - iOS Development: How can I prevent an iPad from running a universal app in iPad mode? iOS开发:如何在设备上引发低内存警告? - iOS Development: How can I induce low memory warnings on device? iOS开发:如何将字符串封装在NSData对象中? - iOS Development: How can I encapsulate a string in an NSData object? 如何在iOS开发中处理自定义事件? - How can I handle custom events in iOS development?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM