在YouTube应用程序中启动YouTube频道

4

为在YouTube应用上播放视频,我正在使用以下代码。

NSURL *instagramURL = [NSURL URLWithString:@"youtube://foo"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
    NSLog(@"opening youtube app...");
    NSString *stringURL = @"http://www.youtube.com/watch?v=H9VdapQyWfg";
    NSURL *url = [NSURL URLWithString:stringURL];
    [[UIApplication sharedApplication] openURL:url];
} else {
    // open in UIWebView in WebViewViewController
    WebViewViewController *secondView = [self.storyboard instantiateViewControllerWithIdentifier:@"webinterface"];

    secondView.headerLabel = @"YouTube";
    secondView.webPath = @"http://www.youtube.com/watch?v=H9VdapQyWfg";

    [self.navigationController pushViewController:secondView animated:YES];
}

现在客户改变了想法,要求将频道放入iPhone应用程序中。
为了测试,我使用了链接http://www.youtube.com/user/richarddawkinsdotnet
但是,当我使用这个链接时,它总是在Safari中打开,而不是Youtube应用程序中。 :(
有什么建议或想法可以通过提供的链接在Youtube应用程序中打开频道吗?
3个回答

12

你的代码出现问题,因为虽然你检查了是否可以正确打开YouTube的URL,但接下来你只是打开了一个网址,这会在Safari中始终打开。

这是我刚刚使用的代码,对我有效。如果您想要回退到使用webviewcontroller,则可能需要修改else语句,因为如果未安装YouTube应用程序,则会在Safari中打开。

NSString *channelName = @"TheNameOfTheChannel";

NSURL *linkToAppURL = [NSURL URLWithString:[NSString stringWithFormat:@"youtube://user/%@",channelName]];
NSURL *linkToWebURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.youtube.com/user/%@",channelName]];

if ([[UIApplication sharedApplication] canOpenURL:linkToAppURL]) {
    // Can open the youtube app URL so launch the youTube app with this URL
    [[UIApplication sharedApplication] openURL:linkToAppURL];
}
else{
    // Can't open the youtube app URL so launch Safari instead
    [[UIApplication sharedApplication] openURL:linkToWebURL];
}

我会检查这个并回复你...我从来没有找到这个答案..希望这个有效.. .:D :P - Fahim Parkar
这对我不起作用!它只是转到应用程序的视频页面并显示“播放错误,点击重试”,但在Safari中打开时正常工作。 - maxisme
如果你想在原生应用程序中打开URL,你应该像这样使用: NSURL *linkToAppURL = @"youtube://www.youtube.com/user/%@",channelName]; .....以下方案将不起作用 NSURL *linkToAppURL = @"youtube://user/%@",channelName]; - Mohammad Rabi
有没有一种方法可以打开特定的视频? - ricardogobbo

1
相同的答案,但更短:

if (![[UIApplication sharedApplication] openURL: [NSURL URLWithString: @"youtube://user/%channelName%"]]) {
  NSURL *webURL = [NSURL URLWithString:@"http://www.youtube.com/user/%channelName%"];
  [[UIApplication sharedApplication] openURL: webURL];
}

和 Twitter:

if (![[UIApplication sharedApplication] openURL: [NSURL URLWithString: @"twitter://user?screen_name=%channelName%"]]) {
  NSURL *webURL = [NSURL URLWithString:@"http://twitter.com/%channelName%"];
  [[UIApplication sharedApplication] openURL: webURL];
}

这里是更详尽的应用程序列表:

http://wiki.akosma.com/IPhone_URL_Schemes


0

youtube://user/<channel-id>iOS 9 中停止工作,因此我进行了研究,并发现它在 iOS 9 中现在可以正常工作。

youtube://www.youtube.com/channel/<channel-id>


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