Goo.gl URL Shortener in iOS短网址服务

 

WAREWOOF

Mobile Design and Development

Main menu

Skip to primary content

Skip to secondary content

  • Home
  • About
  • Contact

 

Post navigation

 Previous

Next 

Goo.gl URL Shortener in iOS

Posted on October 16, 2012

I was having some trouble duplicating the Goo.gl shortener function in Objective C that I had already done in Java, because on the Android version I implemented convenience classes that I had downloaded from the web somewhere.  Examples and freely available classes were not as easy to find for iOS.  So referring to the Goo.gl API, I built the HTTP header using NSString and extracted the result with NSJSONSerialization.

Keep in mind the second portion of this example, didReceiveData method containing class must set NSURLConnectionDataDelegate.  And of course error handling should be considered for cases where connection failed or response was not received, and you may even want to use connectionDidFinishLoading method instead of didReceiveData, but this is the gist of the logic where all the magic happens.  Using Xcode 4.5.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

-(void)shortenMapUrl:(NSString*)originalURL {

 

    NSString* googString = @"https://www.googleapis.com/urlshortener/v1/url";

    NSURL* googUrl = [NSURL URLWithString:googString];

 

    NSMutableURLRequest* googReq = [NSMutableURLRequest requestWithURL:googUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0f];

    [googReq setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    NSString* longUrlString = [NSString stringWithFormat:@"{\"longUrl\": \"%@\"}",originalURL];

 

    NSData* longUrlData = [longUrlString dataUsingEncoding:NSUTF8StringEncoding];

    [googReq setHTTPBody:longUrlData];

    [googReq setHTTPMethod:@"POST"];

 

    NSURLConnection* connect = [[NSURLConnection alloc] initWithRequest:googReq delegate:self];

    connect = nil;

 

}

Within the same class which has set NSURLConnectionDataDelegate will receive the data back, and can be handled as such:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

 

    NSString* returnData = [NSString stringWithUTF8String:[data bytes]];

    NSError* error = nil;

 

    NSArray* jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];

 

    NSString* shortenedURL;

    if (error == nil) {

        if ([jsonArray valueForKey:@"id"] != nil) {

            shortenedURL = [jsonArray valueForKey:@"id"];

        }

    } else {

        NSLog(@"Error %@", error);

    }

 

    NSLog(@"Returned URL: %@", shortenedURL);

 

}

This entry was posted in Objective Csource code by frank. Bookmark the permalink.

Leave a Reply

You must be logged in to post a comment.

 

© 2012 WAREWOOF

 

你可能感兴趣的:(网址,服务)