我已经制作了一个播放YouTube视频的类(感谢这个网站上热心人的帮助)。
现在我想知道如何找出YouTube视频何时开始播放。我想知道这一点,以便在视频被要求播放和实际播放之间显示“请稍候,正在加载…”指示器。
我使用stringByEvaluatingJavaScriptFromString:
来开始播放视频,并且当然,在我触发javascript命令以使视频播放和视频实际播放之间存在轻微延迟。
我熟悉YouTube视频和javascript,所以我一直在查看这个链接:https://developer.apple.com/library/mac/documentation/AppleApplications/Conceptual/SafariJSProgTopics/Tasks/ObjCFromJavaScript.html ,因为我想知道UIWebView内部的javascript事件监听器是否能够检测到YouTube视频何时开始播放(监听onStateChange
事件)并触发Objective C方法。
这可行吗?UIWebViews是否以与Web浏览器相同的方式运行javascript?
还有更简单/更好的方法吗?
这是我的youtube类:
// this is the only property declared in the .h file:
@property (strong, nonatomic) UIView * view
// the rest of this is the .m file:
#import "MyYouTube.h"
@interface MyYouTube()
@property (strong, nonatomic) NSDictionary * contentData;
@property (strong, nonatomic) UIWebView * webView;
@property (nonatomic) int videoOffset;
@end
@implementation MyYouTube
@synthesize view,contentData,webView,videoOffset;
- (MyYouTube*) initIntoView: (UIView*) passedView withContent: (NSDictionary*) contentDict {
NSLog(@"YOUTUBE: begin init");
self=[super init];
videoOffset=0;
view=[[UIView alloc] initWithFrame:passedView.bounds];
[view setBackgroundColor:[UIColor blackColor]];
[view setAutoresizesSubviews:YES];
[view setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth];
contentData=contentDict;
NSString * compiledUrl=[[NSString alloc] initWithFormat:@"http://_xxx_.com/app/youtube.php?yt=%@",[contentData objectForKey:@"cnloc"]];
NSURL * url=[[NSURL alloc] initWithString:compiledUrl];
NSURLRequest * request=[[NSURLRequest alloc] initWithURL:url];
webView=[[UIWebView alloc] initWithFrame:passedView.bounds];
[webView loadRequest:request];
[webView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
[[webView scrollView] setScrollEnabled:NO];
[[webView scrollView] setBounces:NO];
[webView setMediaPlaybackRequiresUserAction:NO];
[webView setDelegate:self];
NSLog(@"YOUTUBE: self: %@",self);
NSLog(@"YOUTUBE: delegate: %@",webView.delegate);
[view addSubview:webView];
NSLog(@"YOUTUBE: end init");
return self;
}
-(void)webViewDidFinishLoad:(UIWebView*)myWebView {
NSLog(@"YOUTUBE: send play command");
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"playVideo(%d)", videoOffset]];
}
@end
许多感谢。