问题
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