0
votes

I'm working on an app which must display a YouTube video when a button is pressed.

I'm using code found elsewhere on the site which appears to function fine under most circumstances, however in my case it is not.

- (void)displayVideo{

CGRect frame = CGRectMake(5,55, 200,310);
    NSLog(@"Trying to display video with ID: %@", videoID);
    NSString *embedHTML =[NSString stringWithFormat:@"\
                          <html><head>\
                          <style type=\"text/css\">\
                          body {\
                          background-color: transparent;\
                          color: white;\
                          }\
                          </style>\
                          </head><body style=\"margin:0\">\
                          <iframe height=\"200\" width=\"310\"      src=\"http://www.youtube.com/embed/%@\"></iframe>\
                          </body></html>", videoID];
    UIWebView *videoView = [[UIWebView alloc] initWithFrame:frame];

    videoView.backgroundColor = [UIColor redColor];
    [videoView loadHTMLString:embedHTML baseURL:nil];
    [self.view addSubview:videoView];
    [self.view setNeedsDisplay]; }

The method is run when the button is pressed. The NSLog goes through fine, so I know the code is being run - the view appears to refuse to update though.

On a whim, I tried putting the code in the ViewController's viewDidLoad method and surprisingly, it worked fine.

Does anyone have any ideas as to why this may be?

1
Are you missing some tiny detail when calling displayVideo? Can you post displayVideo declaration in the .h file? and also the call, as well as from where you are calling it?Eduardo Vieira
I checked your code and it's working for me. I think it is also working for you, just change the background color of your view. (Means set self.view 's background color to green)Midhun MP
I think you need to wait for sometime to see the effect may be your uiwebview is taking time to load, since you were trying on ViewDidAppear which is the last state when a viewcontroller loads..iphonic
The two obvious questions have you confirmed with the debugger that (a) displayVideo is being executed, and (b) videoID has been set at the time it is called?RegularExpression
Don't add UIWebView on button click. Add it in viewDidLoad: method and on button Action just load html string.TheTiger

1 Answers

1
votes

You could add the subview in viewDidLoad, keep them hidden till the button is pressed and then set the value of the hidden property to NO when the button is pressed.

That said I can't see a reason why a view wont be added to the hierarchy outside the viewDidLoad. Since this is a webView I think you could try adding it to the view hierarchy inside the delegate method named - (void)webViewDidFinishLoad:(UIWebView *)aWebView. Don't forget to set the delegate properly.