简体   繁体   中英

objective c open links from UIWebView in safari

I have a UIViewController subclass which includes a UIWebView and implements the UIWebViewDelegate. What i want to do is make links pressed in the UIWebView to open in safari.
I've read past questions about this, but still can't make it work. Here is about what i've done:

In the - (void)viewDidLoad method of my class i use the following code:

[[self articleWebView] setDelegate: self];  
[articleWebView loadRequest:requestObj];

I don't want to display the whole html page that is loaded in the articleWebView object, so in the -(void)webViewDidFinishLoad:(UIWebView *)webView method i use this:
NSString *content = [articleWebView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('myDivId')[0].outerHTML;"];

Then i empty(release) the articleWebView and load the content:

[articleWebView release]; 
articleWebView= [[UIWebView alloc] initWithFrame:CGRectMake(0,0,320,380)];  
[articleWebView loadHTMLString:content baseURL:[NSURL URLWithString:@"http://www.mysite.gr/"]];  
self.view = articleWebView;

I tried to use the following, but it's not working

-(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
    NSURL* url = [request URL];
    if (UIWebViewNavigationTypeLinkClicked == navigationType)
    {
        [[UIApplication sharedApplication] openURL:url];
        return NO;
    }
    return YES;
}

Any ideas what i am missing?
Thank you in advance.

EDIT: As i can see, the shouldStartLoadWithRequest does not get called, so i'm guessing there is something wrong with the delegate of my webView?

I noticed that you are not setting the delegate of "articleWebView" after you release it.

Try using this instead:

[articleWebView release]; 

articleWebView= [[UIWebView alloc] initWithFrame:CGRectMake(0,0,320,380)];  

**articleWebView.delegate = self;** 

[articleWebView loadHTMLString:content baseURL:[NSURL 
URLWithString:@"http://www.mysite.gr/"]];  

self.view = articleWebView;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM