Search code examples
iosuiwebviewappdelegateuiapplicationdelegateuiwebviewdelegate

My first iOS app. I have a UIWebView in my ViewController that I want to update


I have a UIWebView in my ViewController that I want to update when the UIApplicationDelegate is passed a URL, like

myApp://?changeWebView=newstuff

I am building the new URL fine based on the data I am passing in but I can't figure out how to update my UIWebView

I have this in my AppDelegate.m:

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    NSLog(@"Calling Application Bundle ID: %@", sourceApplication);
    NSLog(@"URL scheme:%@", [url scheme]);
    NSLog(@"URL query: %@", [url query]);
    NSLog(@"URL hash: %@", [url fragment]);

    NSURL *newURL = [NSURL URLWithString:@"URL constructed with pieces of passed URL data"];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:newURL];


 //now I want to update the UIWebview defined in my ViewController.h

    return YES;
}

Solution

  • You can load the request in webView by using loadRequest

    [self.myWebView loadRequest:requestObj]; put this line in your code

    You can post notifications to let know your view controller that you can load webview.

    - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
      sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
    {
        NSLog(@"Calling Application Bundle ID: %@", sourceApplication);
        NSLog(@"URL scheme:%@", [url scheme]);
        NSLog(@"URL query: %@", [url query]);
        NSLog(@"URL hash: %@", [url fragment]);
    
        NSURL *newURL = [NSURL URLWithString:@"URL constructed with pieces of passed URL data"];
        NSURLRequest *requestObj = [NSURLRequest requestWithURL:newURL];
    
          //Post Notification
          [[NSNotificationCenter defaultCenter] postNotificationName:@"loadRequest"
                                      object:nil
                                      userInfo:@{@"requestObj":requestObj}];
    
        return YES;
    }
    

    Now in add notification observer in your viewController

    -(void)viewDidLoad{
    
            //Add observer for notification
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveEvent:) name:@"loadRequest" object:nil];
    }
    

    Write this method to load request in webView in your ViewController

    - (void)receiveEvent:(NSNotification *)notification {
        // handle event
            NSURLRequest *requestObj = notification.userInfo[@"requestObj"];
           [self.myWebView loadRequest:requestObj];         
    }