objective c open links from UIWebView in safari

跟風遠走 提交于 2019-12-02 18:08:13

问题


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?


回答1:


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;


来源:https://stackoverflow.com/questions/5899990/objective-c-open-links-from-uiwebview-in-safari

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!