Here is an excerpt from the MyYouTube class where I create a YouTube video:
#interface MyYouTube : NSObject <UIWebViewDelegate>
#end
#implementation
- (void) createYouTubeVideoInView: (UIView*) mainView withContent: (NSDictionary*) contentDict {
// create url request
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];
// create the web view
webView=[[UIWebView alloc] initWithFrame:viewRef.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);
// add the webview to the main view
[mainView addSubview:webView];
}
Here's the thing:
If I set the Delegate to nil then the YouTube video plays fine.
BUT
If I set the Delegate to self then the app crashes and the console shows the following:
YOUTUBE: self: <MyYouTube: 0x16e05f70>
YOUTUBE: delegate: <MyYouTube: 0x16e05f70>
*** -[MyYouTube respondsToSelector:]: message sent to deallocated instance 0x16e2f420
Can anyone explain to me why the instances are different?
Why is there a call to respondsToSelector: on an instance which is different to the delegate? And how can this be fixed?
Many thanks.
I think the reason is that mainView can be released, causing releasing your webview after exiting from createYouTubeVideoInView method.
Insure that mainView is still alive. Place it on another view before calling this method.
And insure that you are having strong reference on MyYouTube object(NSObject). Make it an instance variable, for example.
Related
I'm a newbie in iOS programming, i am trying to make an iOS library that can be useful on my future applications. The app will have a button that will call the library and will load a website(the address link will come from the application).
I tried searching but none of it is working.
WebLibrary.h
#import <Foundation/Foundation.h>
#interface WebLibrary : NSObject
- (void)showUIWebView:(NSURL*)urlToOpen
{
/* UIViewController *myVC = [self.navigationController.viewControllers lastObject];
//This is your last view in the navigationController hierarchy.
UIWebView *newWebView = [[UIWebView alloc] initWithFrame:myVC.view.frame];
[myVC.view addSubview:newWebView];
*/
}
#end
WebLibrary.m
#import "WebLibrary.h"
#implementation WebLibrary
/* -(void) showUIWebView:(NSURL*)urlToOpen
{
//some codes here
}
*/
#end
If you want to load an URL on your webview, you need to call the loadRequest: method to perform it, example:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:_urlPath]];
[request addValue:#"YES" forHTTPHeaderField:#"Mobile-App"];
[_webView loadRequest:request];
You can add the webview to your viewcontroller in viewDidLoad method:
-(void) viewDidLoad{
[super viewDidLoad];
//custom your view
_webView = [[UIWebView alloc] initWithFrame: self.view.frame];
_webView.scalesPageToFit = YES;
[self.view addSubView: _webView];
}
You should read about UIViewController and the methods in it to understand clearly.
I want to load a URL on a UIViewController with an UIWebView and UIActivityIndicatorView, but UIActivityIndicator never appears and UIWebView never loads the URL.
This is my code:
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
self.title = #"Web";
[self displayURL:[NSURL URLWithString:#"(Website)"]];
}
-(void) webViewDidFinishLoad:(UIWebView *)webView {
[self.loadView stopAnimating];
self.loadView.hidden = YES;
}
-(void) displayURL:(NSURL *) aURL {
self.web.delegate = self;
self.loadView.hidden = NO;
[self.loadView startAnimating];
[self.web loadRequest:[NSURLRequest requestWithURL:aURL]];
}
If you add your webView by code, you need add
[self.view addSubview: web];
after you created webView, and of course you need to add UIActivityIndicatorView as a subView of webView or superView, so you need to add [web addSubview: loadView] or [self.view insertSubview: loadView aboveSubview: web];.
And about the URL, if your website URL is like www.google.com, you need to change #"(Website)" to the real URL. If your website is a file copied in your project, you need to change [NSURL URLWithString: ]; to [NSURL fileURLWithPath:[NSBundle mainBundle][pathForResource: ofType:]];.
Really poorly formulated question.
UIWebViewController does not work
UIWebViewController does not exists, you are talking about a UIWebView in a UIViewController
Code is very incomplete
In my app, I am trying to make a splash image appear as my UIWebView loads so it is not just a blank screen. However my webViewDidFinishLoad method will not work. This means that the splash image appears but does not disappear from the screen once the UIWebView has loaded.
My code for the method is:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSLog(#"content loading finished");
[loadingImageView removeFromSuperview];
}
Any help on why the method will not work would be appreciated greatly.
My .h:
#interface ViewController : UIViewController
-(IBAction)makePhoneCall:(id)sender;
#property (nonatomic, strong) IBOutlet UIWebView *webView;
#property(nonatomic, strong) UIImageView *loadingImageView;
#end
My ViewDidLoad and webViewDidFinishLoading:
- (void)viewDidLoad {
UIWebView *mWebView = [[UIWebView alloc] init];
mWebView.delegate = self;
mWebView.scalesPageToFit = YES;
[super viewDidLoad];
}
//**************** Set website URL for UIWebView
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.sleafordpizza.com/food"]]];
//**************** Add Static loading image to prevent white "flash" ****************/
UIImage *loadingImage = [UIImage imageNamed:#"LittleItalyLogo.png"];
loadingImageView = [[UIImageView alloc] initWithImage:loadingImage];
loadingImageView.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:#"LittleItalyLogo.png"],
nil];
[self.view addSubview:loadingImageView];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSLog(#"content loading finished");
// Remove loading image from view
[loadingImageView removeFromSuperview];
}
Hi probably you do not set proper delegate.
This is small code tip for you.
-(void)viewDidLoad {
mWebView = [[UIWebView alloc] init];
mWebView.delegate = self;
mWebView.scalesPageToFit = YES;
}
-(void)webViewDidFinishLoad:(UIWebView *)webView {
[loadingImageView removeFromSuperview];
NSLog(#"finish");
}
In you're .h file add.
#interface MyView: UIViewController <UIWebViewDelegate> {
UIWebView *webView;
}
Code fixes.
For .h file
#interface ViewController : UIViewController<UIWebViewDelegate>
-(IBAction)makePhoneCall:(id)sender;
#property (nonatomic, strong) IBOutlet UIWebView *webView;
#property(nonatomic, strong) UIImageView *loadingImageView;
#end
For .m file
- (void)viewDidLoad
{
[super viewDidLoad];
webView.delegate = self;
//**************** Set website URL for UIWebView
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.sleafordpizza.com/food"]]];
//**************** Add Static loading image to prevent white "flash" ****************/
UIImage *loadingImage = [UIImage imageNamed:#"LittleItalyLogo.png"];
loadingImageView = [[UIImageView alloc] initWithImage:loadingImage];
loadingImageView.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:#"LittleItalyLogo.png"],
nil];
[self.view addSubview:loadingImageView];
}
At certain times, this delegate method actually never gets fired. I have had severe problems with the same thing in some of my projects.
At one occasion, I actually had to solve it with a timer, checking the state of the web view every second or so to see if I could proceed.
In that particular case, I just needed a certain element to be present. Still, the view did not trigger the finish loading event, due to external script errors being injected.
So, I just started a trigger when the web view begun loading, then called a method every now and then to see if the web view contained the element in question.
- (void)methodCalledByTimer {
if (<I still do not have what I need>) {
//The web view has not yet finished loading; keep checking
} else {
//The web view has finished loading; stop the timer, hide spinners and proceed
}
}
You could also check if the web view is actually loading, if that is absolutely necessary:
- (void)methodCalledByTimer {
if (self.webView.isLoading) {
//The web view has not yet finished loading; keep checking
} else {
//The web view has finished loading; stop the timer, hide spinners and proceed
}
}
Then, naturally, I'd check for the finishedLoading event as well, just to be sure. Remember to also implement the webView:didFailLoadWithError: method as well.
When waiting for a web page to finish loading, there are some things to keep in mind.
For instance, do you really need it to stop loading, or is there anything else you can do? In my case, I needed an element. Being able to properly execute a script is another thing that may be required.
Second, is the loading page using any external resources? I once had external script errors causing the webViewDidFinishLoad: method to not being called at all. If I removed the external scripts, it worked.
Third, if the page is using external resources, you are exposed not only to the loading capacity of your own resources, but that of the external resources as well. Tracking scripts, ads etc...if one resource provider is delivering content sloooowly (or not at all), you could page could be stuck in loading state forever.
So, I'd go with checking for something else. :)
I see you aren't handling errors. If there is an error, all subsequent delegate calls will not happen. I was surprised to find that this is true when the webview uses a plugin too. It calls this error method telling you that the webview handed off to the delegate, in my case the movie player.
implement this and see if that is it.
-(void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
if (error.code == 204) {
//request was handled by a plugin instead of by the webview directly
...
}
else
{
NSLog(#"didFailLoadWithError. ERROR: %#", error);
}
}
I was able to do all the remaining loading work in this method instead of the webviewdidfinishLoad
I have implemented a browser in my application by using UIWebView, by default I'm loading google page in my browser.
When I search something in the google page ,the UIWebViewDelegate's webView:shouldStartLoadWithRequest:navigationType: method is called.
The problem is when I tap on the back button from this search page no delegates are getting called, so I am having a problem disabling my back button.
This problem happens only in an iPad application not in an iPhone application.
This code may help u...
A UIWebView is a UIView that can load a web page while remaining in the user's application.
Navigation to other webpages is allowed through the use of imbedded links in a web page itself. Forward and backward navigation through history can be set up with instance methods goForward and goBack, but the programmer must supply the buttons.
The following example uses a UIWebView, and
1) adds forward and backward buttons. The buttons are enabled and highlighted using UIWebViewDelegate optional methods webViewDidStartLoad: and webViewDidFinishLoad:
2) adds a UIActivityIndicatorView which displays while the web page is loading
In the .h file for the WebViewController :
Declare the UIWebView, Optionally : add buttons to control moving forward and backward through browsing history and IBActions for pressing the buttons, Optionally again : add a UIActivityIndicatorView.
#interface WebViewController : UIViewController <UIWebViewDelegate>
{
UIWebView *webView;
UIButton *back;
UIButton *forward;
UIActivityIndicatorView *activityIndicator;
}
#property(nonatomic,retain)IBOutlet UIWebView *webView;
#property(nonatomic,retain)IBOutlet UIButton *back;
#property(nonatomic,retain)IBOutlet UIButton *forward;
#property(nonatomic,retain)IBOutlet UIActivityIndicatorView *activityIndicator;
-(IBAction)backButtonPressed: (id)sender;
-(IBAction)forwardButtonPressed: (id)sender;
#end
//In the .m file for the WebViewController
#implementation WebViewController
#synthesize webView;
#synthesize back;
#synthesize forward;
#synthesize activityIndicator;
//method for going backwards in the webpage history
-(IBAction)backButtonPressed:(id)sender {
[webView goBack];
}
//method for going forward in the webpage history
-(IBAction)forwardButtonPressed:(id)sender
{
[webView goForward];
}
//programmer defined method to load the webpage
-(void)startWebViewLoad
{
//NSString *urlAddress = #"http://www.google.com";
NSString *urlAddress = #"http://cagt.bu.edu/page/IPhone-summer2010-wiki_problemsandsolutions";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webView loadRequest:requestObj];
}
// acivityIndicator is set up here
- (void)viewDidLoad
{
//start an animator symbol for the webpage loading to follow
UIActivityIndicatorView *progressWheel = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
//makes activity indicator disappear when it is stopped
progressWheel.hidesWhenStopped = YES;
//used to locate position of activity indicator
progressWheel.center = CGPointMake(160, 160);
self.activityIndicator = progressWheel;
[self.view addSubview: self.activityIndicator];
[self.activityIndicator startAnimating];
[progressWheel release];
[super viewDidLoad];
//call another method to do the webpage loading
[self performSelector:#selector(startWebViewLoad) withObject:nil afterDelay:0];
}
- (void)dealloc
{
[webView release];
[back release];
[forward release];
[activityIndicator release];
[super dealloc];
}
#pragma mark UIWebViewDelegate methods
//only used here to enable or disable the back and forward buttons
- (void)webViewDidStartLoad:(UIWebView *)thisWebView
{
back.enabled = NO;
forward.enabled = NO;
}
- (void)webViewDidFinishLoad:(UIWebView *)thisWebView
{
//stop the activity indicator when done loading
[self.activityIndicator stopAnimating];
//canGoBack and canGoForward are properties which indicate if there is
//any forward or backward history
if(thisWebView.canGoBack == YES)
{
back.enabled = YES;
back.highlighted = YES;
}
if(thisWebView.canGoForward == YES)
{
forward.enabled = YES;
forward.highlighted = YES;
}
}
#end
/*****************************/
//In viewDidLoad for the class which adds the WebViewController:
WebViewController *ourWebVC = [[WebViewController alloc] initWithNibName:#"WebViewController" bundle:nil];
ourWebVC.title = #"WebView";
[self.view addSubview:ourWebVC];
//release ourWebVC somewhere else
In your case ,You have to ignore/avoid "caching data". Following lines of code may help.
NSURLRequest *requestObj = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.google.com"] cachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10.0];
[webView loadRequest:requestObj];
I've using shouldStartLoadWithRequest very successfully in one of my programs, but the whole project was a proof of concept and scruffy and I'm starting afresh with a new project.
However shouldStartLoadWithReqest is no longer being invoked for me but I can't see where the important difference between the two projects is (however one difference is the first is using .nibs, in the 2nd I'm not using them).
To get things started I'm using a controller with the UIWebView as its view:
#interface IMSRootController : UIViewController <UIWebViewDelegate> {
UIWebView* webView;
}
(webView is declared as a #property and #synthesized)
- (void)loadView {
[super loadView];
webView = [[UIWebView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.view = webView;
[webView release]; }
- (void)viewDidLoad {
[super viewDidLoad];
[[self navigationController] setNavigationBarHidden:YES animated:NO];
[self displayPage]; }
-(void) displayPage { ... [webView loadHTMLString:self.htmlString baseURL:baseURL]; }
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
...
What's wrong?
Thanks
Your object is not being set as a delegate of the UIWebView object, hence you will not receive any delegate messages. At some point, either in loadView or even displayPage (but before the call to loadHTMLString:baseURL:), do:
webView.delegate = self;