我在获取通过 UIWebView 嵌入到我正在制作的 iOS 应用程序中的视频时遇到一些问题。 iframe 播放器加载完全正常,但是当我点击播放按钮时,白色旋转器出现一秒钟然后消失,只留下一个黑框如果我触摸黑框,我会得到标题和“i”按钮,但是视频永远不会开始。
我发现播放视频的唯一方法是点击右上角的“i”按钮查看信息,然后再次按下该按钮将触发全屏播放器。我只是不明白为什么它不会在第一次按下时播放。
这是我用来创建 HTML 和嵌入 YouTube 视频的完整代码
- (void)setupHTMLString
{
//NSData *data = [[NSData alloc] init];
NSString *imageString = [NSData htmlForJPEGImage:[UIImage imageWithData:self.post.thumbnail]];
NSString *htmlString = @"<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"></head><body>";
htmlString = [htmlString stringByAppendingString:@"<div id=\"content\" style=\"width:304px\">"];
NSString *titleString = [NSString stringWithFormat:@"<h1>%@</h1> ", self.post.title];
NSString *authorString = [NSString stringWithFormat:@"<h3>By %@</h3>", [self returnAuthorName]];
NSString *contentString = [NSString stringWithFormat:@"<p>%@</p>", [self createStringWithURLsFromString:self.post.content]];
NSString *postString = [NSString stringWithFormat:@"%@ %@ %@ %@", imageString, titleString, authorString, contentString];
htmlString = [htmlString stringByAppendingString:postString];
htmlString = [htmlString stringByAppendingString:@"</div?></body></html>"];
NSLog(@"%@", htmlString);
// UIWebView uses baseURL to find style sheets, images, etc that you include in your HTML.
NSURL *bundleUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[self.webView loadHTMLString:htmlString baseURL:bundleUrl];
self.webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, INSETHEIGHT, 0);
self.webView.scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, INSETHEIGHT, 0);
}
- (NSString *)createStringWithURLsFromString:(NSString *)string
{
NSString *regexToReplaceRawLinks = @"(?:https?:)?//(?:[^.]*\\.)?youtu(?:\\.be|be\\.com)(?:/|/embed/|/v/|/watch/?\?(?:.+&)?v=)([\\w-]{11})";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexToReplaceRawLinks
options:NSRegularExpressionCaseInsensitive
error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:@"<iframe class=\"youtube-player\" type=\"text/html\" width=\"320\" height=\"180\" src=\"http://www.youtube.com/embed/$1\" frameborder=\"0\"></iframe>"];
//NSLog(@"%@", modifiedString);
return modifiedString;
}