Lucas Veiga Lucas Veiga - 1 month ago 10
iOS Question

Can't Change URL in WebView

i'm trying to change a url from a webview when I receive an action, which in handled by the method below. The method works, but the webview url is never changed.

- (void)viewDidLoad {
[super viewDidLoad];
myWebView.delegate = self;
NSString *fullURL = @"http://cardapiomestre.com.br/beta";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[myWebView loadRequest:requestObj];
}


The method:

-(void) setWebViewURL:(NSString*)url
{
NSString *urlAddress = url;
NSURL *essaUrl = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:essaUrl];
[self.myWebView loadRequest:requestObj];
}


The url from setWebViewURL param it's a valid URL. I even tried to set the url manually but it didn't work.

I call it on AppDelegate.m:

ViewController* myScript = [[ViewController alloc] init];
[myScript setWebViewURL:@"http://google.com"];


Any advice?

Thanks

Answer

In the appDelegate, instead of doing:

ViewController* myScript = [[ViewController alloc] init];
[myScript setWebViewURL:@"http://google.com"];

Here you are creating a new instance of your view controller and by this way your webView will be nil, hence you are not seeing the expected result.

You should post a notification in app delegate:

[[NSNotificationCenter defaultCenter] postNotificationName:@"refreshWebView" object:nil];

and in your viewController, listen to this notification:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadWebView) name:@"refreshWebView" object:nil];

and in your view controller, define method:

-(void)reloadWebView{
    NSString *urlAddress = @"your-url";
    NSURL *essaUrl = [NSURL URLWithString:urlAddress];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:essaUrl];
    [self.myWebView loadRequest:requestObj];
}