打开iTunes Store到特定歌曲

5

好的,我在这里看到了一些类似的问题,但是没有一个实际上解决我的问题。

我有一个流媒体音频应用程序,流媒体源会返回给我歌曲标题和艺术家姓名。我在应用程序中有一个iTunes按钮,并希望打开iTunes STORE(搜索)到那首歌曲,或者至少靠近那个位置。我尝试了以下方法:


NSString *baseString = @"itms://phobos.apple.com/WebObjects/MZSearch.woa/wa/advancedSearchResults?songTerm=";

NSString *str1 = [self.songTitle2 stringByReplacingOccurrencesOfString:@" " withString:@"+"];

NSString *str2 = [self.artist2 stringByReplacingOccurrencesOfString:@" " withString:@"+"];

NSString *str = [NSString stringWithFormat:@"%@%@&artistTerm=%@", baseString, str1, str2];

[[UIApplication sharedApplication] openURL: [NSURL URLWithString:str]];

这个调用确实像预期的一样将我切换到iTunes STORE,但是它弹出了一个错误提示:“无法连接到iTunes Store”。显然,我在线上,因为歌曲正在流畅播放,而且我在商店里。iTunes应用中的搜索框只显示歌曲名称,没有其他信息。

以下是生成的字符串示例: itms://phobos.apple.com/WebObjects/MZSearch.woa/wa/advancedSearchResults?artistTerm=Veruca+Salt&artistTerm=Volcano+Girls

我已经尝试把生成的字符串复制并粘贴到Safari中,在我的Mac上运行良好,打开该艺术家在商店中的专辑。为什么电话不能运行呢?

此外,似乎忽略了两个条目,因为它没有带我去那位艺术家的歌曲。这是否还需要知道专辑名称(我现在没有)。

欢迎提供帮助。谢谢。


谢谢Alex。我不确定该怎么做! :-) - MajorHavoc
编辑标题以提及商店 - Daij-Djan
哦,我的错。我想要打开iTunes STORE,而不是iTunes本身。感谢Daj-Djan编辑。我也会编辑问题。 - MajorHavoc
你所使用的示例并没有使用 songTerm,而是两次使用了 artistTerm。 - Fábio Oliveira
3个回答

8
是的,我正在回答自己的问题。
经过深入挖掘和与我认识的最好的程序员之一的交谈,我们找到了一个解决方案,所以我想在这里分享一下。该解决方案获取歌曲名称和艺术家,并实际调用Link Maker API,获取一个XML文档,并提取必要的信息来创建指向iTunes Store的链接,打开包含该歌曲的艺术家专辑中的歌曲的商店。
在视图控制器的接口中添加:
@property (strong, readonly, nonatomic) NSOperationQueue* operationQueue;
@property (nonatomic) BOOL searching;

在实现中:

@synthesize operationQueue = _operationQueue;
@synthesize searching = _searching;

以下是可以帮助您完成此操作的方法和代码:
// start an operation Queue if not started
-(NSOperationQueue*)operationQueue
{
    if(_operationQueue == nil) {
        _operationQueue = [NSOperationQueue new];
    }
    return _operationQueue;
}
// change searching state, and modify button and wait indicator (if you wish)
- (void)setSearching:(BOOL)searching
{
// this changes the view of the search button to a wait indicator while the search is     perfomed
// In this case
    _searching = searching;
    dispatch_async(dispatch_get_main_queue(), ^{
        if(searching) {
            self.searchButton.enabled = NO;
            [self.searchButton setTitle:@"" forState:UIControlStateNormal];
            [self.activityIndicator startAnimating];
        } else {
            self.searchButton.enabled = YES;
            [self.searchButton setTitle:@"Search" forState:UIControlStateNormal];
            [self.activityIndicator stopAnimating];
        }
    });
}
// based on info from the iTunes affiliates docs
// http://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html
// this assume a search button to start the search. 
- (IBAction)searchButtonTapped:(id)sender {
    NSString* artistTerm = self.artistField.text;  //the artist text.
    NSString* songTerm = self.songField.text;      //the song text 
    // they both need to be non-zero for this to work right.
    if(artistTerm.length > 0 && songTerm.length > 0) {

        // this creates the base of the Link Maker url call.

        NSString* baseURLString = @"https://itunes.apple.com/search";
        NSString* searchTerm = [NSString stringWithFormat:@"%@ %@", artistTerm, songTerm];
        NSString* searchUrlString = [NSString stringWithFormat:@"%@?media=music&entity=song&term=%@&artistTerm=%@&songTerm=%@", baseURLString, searchTerm, artistTerm, songTerm];

        // must change spaces to +
        searchUrlString = [searchUrlString stringByReplacingOccurrencesOfString:@" " withString:@"+"];

        //make it a URL
        searchUrlString = [searchUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL* searchUrl = [NSURL URLWithString:searchUrlString];
        NSLog(@"searchUrl: %@", searchUrl);

        // start the Link Maker search
        NSURLRequest* request = [NSURLRequest requestWithURL:searchUrl];
        self.searching = YES;
        [NSURLConnection sendAsynchronousRequest:request queue:self.operationQueue completionHandler:^(NSURLResponse* response, NSData* data, NSError* error) {

            // we got an answer, now find the data.
            self.searching = NO;
            if(error != nil) {
                NSLog(@"Error: %@", error);
            } else {
                NSError* jsonError = nil;
                NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
                if(jsonError != nil) {
                    // do something with the error here
                    NSLog(@"JSON Error: %@", jsonError);
                } else {
                    NSArray* resultsArray = dict[@"results"];

                    // it is possible to get no results. Handle that here
                    if(resultsArray.count == 0) {
                        NSLog(@"No results returned.");
                    } else {

                        // extract the needed info to pass to the iTunes store search
                        NSDictionary* trackDict = resultsArray[0];
                        NSString* trackViewUrlString = trackDict[@"trackViewUrl"];
                        if(trackViewUrlString.length == 0) {
                            NSLog(@"No trackViewUrl");
                        } else {
                            NSURL* trackViewUrl = [NSURL URLWithString:trackViewUrlString];
                            NSLog(@"trackViewURL:%@", trackViewUrl);

                           // dispatch the call to switch to the iTunes store with the proper search url
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [[UIApplication sharedApplication] openURL:trackViewUrl];
                            });
                        }
                    }
                }
            }
        }];
    }
}

XML文件中还有很多其他有用的信息,可以提取出来,包括三种大小的专辑封面、专辑名称、价格等等。

希望这能帮助其他人。我被这个问题困扰了相当长时间,感谢我的好朋友让这个方法奏效。


1
一个快速的提示:返回的数据是JSON格式,而不是XML。否则,感谢提供的信息! - MattLoszak
是的,我的错,我打字很快,XML就从手指中流出来了。你是正确的,返回的是JSON数据。 - MajorHavoc

0

你实际上是在使用一个URL来进行搜索。这就是为什么iTunes会在搜索时打开。我的Mac OS X上的iTunes也会在搜索时打开。

使用iTunes搜索API来搜索你想要的内容,并获取艺术家、专辑或歌曲的ID,以便你可以生成该内容的直接URL。

查看iTunes链接生成器,了解如何为艺术家或特定专辑创建URL,并在你的应用程序中组成该URL。


谢谢Fabio。我意识到我在问题上没有表达清楚。实际上,我的意思是我想让iTunes STORE在搜索时打开(我修正了问题),所以这是我期望的行为。我已经看过iTunes链接制造器,并且可以轻松手动创建一个,但是我不知道如何从应用程序(使用Objective-C)中使用链接制造器,在其中歌曲名称和艺术家是动态的,一直在变化,因此我可以在我的代码中动态地创建该链接。我也没有专辑名称或ID,只有歌曲名和艺术家。我仍然应该能够看到专辑列表。这就是困扰我的事情。 - MajorHavoc
我还要补充的是,它确实按预期打开以进行搜索,但然后我收到了无法连接到商店的错误,这仍然让我感到困惑。谢谢。 - MajorHavoc
好的,我明白了。你无法从应用程序中使用链接制造器(也许如果你检查所做的POST请求,你可以直接这样做),但它实际上并不生成搜索链接。 - Fábio Oliveira
为什么不使用搜索API并在应用内显示项目,然后在获取特定专辑或歌曲的ID时链接到商店?目前,我认为您在iOS iTunes Store上显示搜索的要求是问题,因为没有高级搜索。 - Fábio Oliveira

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接