Thursday, September 8, 2011

Using APIs for Cocoa Touch (Objective-C)

This segment of code is to extract data from the Lyrics API from chartlyrics.com. It's great because there's no API key, and the code is relatively simple.  This finds the element lyric in the XML return, and saves it into an NSSTRING.

Code:

NSString * artist =  @"artist name";
NSString * song =  @"&song=";
NSString * songTitle =  @"song name";
[song appendFormat:@"%d", songTitle];
NSString * address = @"http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=”;
NSString * request = [NSString stringWithFormat:@"%@%@%@",address,artist,song];
NSURL * URL = [NSURL
URLWithString:request];
NSError * error;  
NSString* XML = [NSString stringWithContentsOfURL:URL encoding:NSASCIIStringEncoding error:&error];

// Extract lyric the by scanning elements
NSString * lyric = [[[[XML componentsSeparatedByString:@"Lyric=\""] objectAtIndex:1] componentsSeparatedByString:@"\""] objectAtIndex:0];
NSLog(@"%@", lyric);

No comments:

Post a Comment