问题
When Running the app it first loads, then loads the web page in safari. How would I make the page load in the UIWebView
and have the external links in the webView
open in safari?
Here is some of the Code of The webviewcontroller.m -
#import "WebViewController.h"
@implementation WebViewController
@synthesize webView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Initialization code
}
return self;
}
/*
If you need to do additional setup after loading the view, override viewDidLoad. */
- (void)viewDidLoad {
NSString *urlAddress = @"url link goes here";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
[[UIApplication sharedApplication] openURL:url];
//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webView loadRequest:requestObj];
}
@end
回答1:
The reason the first page is loading in Safari instead of your UIWebView
in your app is this line of code:
[[UIApplication sharedApplication] openURL:url];
Remove this line from your viewDidLoad
method.
In order to make links inside your webView
load in the Safari app, first set your view controller as the delegate for the webView with webView.delegate = self;
inside the viewDidLoad
method.
Then add the following code to your viewController
:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked)
{
[[UIApplication sharedApplication] openURL:request.URL];
return NO;
}
return YES;
}
This method will get called every time the webView
is about to start loading a request. What it does is check if the request was initiated by a click by the user. In case it was, it opens Safari and loads the request there. Any other requests that were not initiated by a click are loaded within your application, such as the request for your start page.
来源:https://stackoverflow.com/questions/15537289/open-webview-links-in-safari