0

I am trying to override URL clicks in a UIWebView object. I know that I need to add the following code at the place where the 'webView delegate is set' (according to this thread):

// TODO: This should intercept URL clicks in a UIWebView, causing (for now) links to open in Safari. It doesn't work yet; possibly it's in the wrong place. Should be in the same place as we 'set the webView delegate'...
// This doesn't appear to be set anywhere yet, which is probably where I'm going wrong.
- (BOOL)webView: (UIWebView*)webView shouldStartLoadWithRequest: (NSURLRequest*)request navigationType: (UIWebViewNavigationType)navigationType {

    if ( navigationType == UIWebViewNavigationTypeLinkClicked ) {
        [[UIApplication sharedApplication] openURL:[request URL]];
        return NO;
    }

    return YES;
}

However, I have no idea where to actually put the code. One suggestion on the above thread is to place it in the viewDidLoad method, underneath a line that says "self.webView.delegate = self;". However, my UIWebViews are actually part of a custom UIView which is called upon much like a UIAlertView (in fact, it is almost an exact replica of a UIAlertView, except that it contains a UIWebView)... So, my main app's ViewController code does not 'see' the self.webView object, so I can't set the delegate there. And, the 'm' file that specifies my custom UIView object (which calls the UIWebView object) doesn't have a viewDidLoad method.

Really struggling with this, presumably because I don't know where delegates are set.

Community
  • 1
  • 1
CaptainProg
  • 5,610
  • 23
  • 71
  • 116

1 Answers1

1

And, the 'm' file that specifies my custom UIView object (which calls the UIWebView object) doesn't have a viewDidLoad method.

Put it in the - initWithFrame: method then:

- (id)initWithFrame:(CGRect)frm
{
    if ((self = [super initWithFrame:frm])) {
         webView = [[UIWebView alloc] initWithFrame:frm]; // or whatever

         self.webView.delegate = self;
    }
    return self;
}
  • Thanks! This works a treat. I *do* get a warning though; Assigning to 'id' from incompatible type '*'. Seems to work though... Thanks! – CaptainProg Oct 30 '12 at 23:29
  • .. so I can ignore the warning? – CaptainProg Oct 30 '12 at 23:33
  • @CaptainProg no. Make your view class conform to the `UIWebViewDelegate` protocol. –  Oct 30 '12 at 23:34
  • @CaptainProg Never ignore warnings. All code should compile clean. – rmaddy Oct 30 '12 at 23:40
  • Does this mean I need to include all four of the 'tasks' on this page? http://developer.apple.com/library/ios/#documentation/uikit/reference/UIWebViewDelegate_Protocol/Reference/Reference.html – CaptainProg Oct 30 '12 at 23:45
  • 1
    @CaptainProg nope. Add `` to the declaration of your class `@interface`, and **read a comprehensive Objective-C tutorial.** –  Oct 30 '12 at 23:47