Raymond
Raymond

Reputation: 477

UIWebView Launch in Safari

I know that this has been brought up many a times and answered twice as many on this site, however I think I may have something a little different and need to know if it is possible.

I am trying to load a banner ad from a website into a UIWebView in the app. All of this works flawlessly. However no matter what code I have tried to implement I cannot get it so that when the ad is clicked in the app it will launch in safari.

Basically I am wanting to have my own Ad server. The ad is managed ad hosted on our site. The banner has the link embedded into it by the server.

Here is the code I am using.

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

    NSString *string;
    string = @"http://www.samplesite.com/mobile_ads";
    NSURL *url = [NSURL URLWithString: string];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [self.adBox loadRequest:requestObj];
}

-(BOOL) adBox:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest    navigationType:(UIWebViewNavigationType)inType {
if ( inType == UIWebViewNavigationTypeLinkClicked ) {
    [[UIApplication sharedApplication] openURL:[inRequest URL]];
    return NO;
}

return YES;
}

Any ideas of where I should go?

Upvotes: 1

Views: 198

Answers (1)

Ben S
Ben S

Reputation: 69382

In your UIWebViewDelegate's webView:shouldStartLoadWithRequest:navigationType: method, do something like the following (assuming your ads have part of their URL identifiable):

- (void)methodThatCreatesTheWebview {
  UIWebView *webview = [[UIWebView alloc] init];
  webview.delegate = self;
}


// Portion of the URL that is only present on ads and not other URLs.
static NSString * const kAd = @"adSubdominOrSubDirectory";

// pragma mark - UIWebViewDelegate Methods

- (BOOL)webView:(UIWebView *)webView
    shouldStartLoadWithRequest:(NSURLRequest *)request
                navigationType:(UIWebViewNavigationType)navigationType
{
  if ([request.URL.absoluteString rangeOfString:kAd] !=  NSNotFound) {
    // Launch Safari to open ads
    return [[UIApplication sharedApplication] openURL:request.URL];
  } else {
    // URL isn't an ad, so just load it in the webview.
    return YES;
  }
}

Upvotes: 1

Related Questions