根据TVrage的API 搞了个检索的Demon。
http://services.tvrage.com/info.php?page=main
更新了部分代码,修复检索多个单词不响应,改变搜索方案为输入完整后Enter才执行。
下面是核心部分代码
- (NSArray *)fetchTVShowWithTitle:(NSString *)title WithError:(NSError **)outError
{
BOOL success;
NSURL *xmlURL = [NSURL URLWithString:[@"http://services.tvrage.com/feeds/search.php?show=" stringByAppendingString:[title stringByReplacingOccurrencesOfString:@" " withString:@"%20"]]];
//NSLog(@"xml is%@",xmlURL);
NSURLRequest *req = [NSURLRequest requestWithURL:xmlURL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];
NSURLResponse *resp = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&resp error:outError];
if (!data)
return nil;
[shows removeAllObjects];
NSXMLParser *parser;
parser = [[NSXMLParser alloc]initWithData:data];
[parser setDelegate:self];
success = [parser parse];
if (!success) {
*outError = [parser parserError];
return nil;
}
NSArray *output = [shows copy];
return output;
}
#pragma mark -
#pragma mark NSXMLParserDelegate Methods
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"show"]) {
currentFields = [[NSMutableDictionary alloc]init];
}else if ([elementName isEqualToString:@"genres"]){
currentGenres = [[NSMutableArray alloc]init];}
}
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:@"show"]) {
TVShow *currentShow = [[TVShow alloc]init];
[currentShow setShowid:[currentFields
objectForKey:@"showid"]];
[currentShow setName:[currentFields
objectForKey:@"name"]];
[currentShow setLink:[currentFields
objectForKey:@"link"]];
[currentShow setCountry:[currentFields
objectForKey:@"country"]];
[currentShow setClassification:[currentFields
objectForKey:@"classification"]];
NSString *genres = [currentGenres componentsJoinedByString:@"|"];
[currentShow setGenres:genres];
[shows addObject:currentShow];
currentShow = nil;
currentFields = nil;
currentGenres = nil;
}
else if (currentFields && currentString)
{
NSString *trimmed;
trimmed = [currentString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[currentFields setObject:trimmed forKey:elementName];
if ([elementName isEqualToString:@"genre"]){
[currentGenres addObject:[currentFields objectForKey:@"genre"]];}
}
currentString = nil;
}
- (void)parser:(NSXMLParser *)parser
foundCharacters:(NSString *)string
{
if (!currentString) {
currentString = [[NSMutableString alloc] init];
}
[currentString appendString:string];
}
效果图: