在iOS中通过代码我想打开iTunes并搜索通过代码传递的特定字符串

时间:2014-06-30 05:03:55

标签: ios objective-c

- (IBAction)purchaseButtonTapped:(id)sender {
    NSString *iTunesLink =[NSString stringWithFormat:@"itms://itunes.com/%@",[self urlStringForSong:[songNameLabel text]]];
    iTunesLink=[iTunesLink stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];
}

-(NSString *)urlStringForSong:(NSString *)songName
{
    songName=[songName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //remove mutilpe spaces by single space character
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"  +" options:NSRegularExpressionCaseInsensitive error:&error];
    songName=[regex stringByReplacingMatchesInString:songName options:0 range:NSMakeRange(0, [songName length]) withTemplate:@" "];

    NSCharacterSet *cs=[[NSCharacterSet characterSetWithCharactersInString:@"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM1234567890.-_* "] invertedSet];
    songName=[[songName componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""];
        return songName;
}

2 个答案:

答案 0 :(得分:0)

如果您想搜索媒体,可以从中获取帮助 itunesLinkMaker

hit this url with parameters you will get response json for searched results.
https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/wsSearch?term=**asd**&country=US&media=music&entity=song&limit=25&genreId=&version=2&output=json&callback=jQuery18302224650508724153_1404104878083&_=1404104902716

您可以尝试Itunes Search APi这将指导您完成从iTunes搜索的演示。

答案 1 :(得分:0)

你的问题是你没有逃离空间。您不能只在URL中放置空格,它不会正确解析,因此您必须使用%20来转义它。 %转义字符,20是空格的十六进制ASCII代码。

替换此行:

songName=[regex stringByReplacingMatchesInString:songName options:0 range:NSMakeRange(0, [songName length]) withTemplate:@" "];

使用:

songName=[regex stringByReplacingMatchesInString:songName options:0 range:NSMakeRange(0, [songName length]) withTemplate:@"%20"]; // Notice the %20 instead of a space

See this link for more URL Escape Codes