Open links in safari instead of inside webview - ios

I am a beginner in making iOS applications. I have made a simple webview showing my web page. The problem is that every link that is pressed in my web page opens in the webview. I want some links to open in safari. I would like links starting with "..something" to be opened inside the webview and every other link to be opened in safari. I also have a button for email and dial which i want to open in the dial app and email app on the phone. Is this a possibility? please explain simple.
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (nonatomic, strong) IBOutlet UIWebView *webView;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize webView;
- (void)viewDidLoad
{
NSURL *url = [NSURL URLWithString:#"http://MyWebPage"];
NSURLRequest *requestURL = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestURL];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
I made the same application for android using java with this code below
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
try{
System.out.println("url called:::" + url);
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
} else if (url.startsWith("http:")
|| url.startsWith("https:")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
} else if (url.startsWith("mailto:")) {
MailTo mt=MailTo.parse(url);
send_email(mt.getTo());
}
else {
return false;
}
}catch(Exception e){
e.printStackTrace();
}
return true;
}
}

You'll need to make your controller a UIWebViewDelegate and implement the webView: shouldStartLoadWithRequest:navigationType: method.
#interface ViewController () <UIWebViewDelegate>
viewDidLoad should look like this:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSURL *url = [NSURL URLWithString:#"http://MyWebPage"];
NSURLRequest *requestURL = [NSURLRequest requestWithURL:url];
webView.delegate = self;
[webView loadRequest:requestURL];
}
- (BOOL)webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
if ( inType == UIWebViewNavigationTypeLinkClicked && [self shouldOpenInSafari:[inRequest URL]]) {
[[UIApplication sharedApplication] openURL:[inRequest URL]];
return NO;
}
return YES;
}
- (BOOL)shouldOpenInSafari:(NSURL*)url
{
if ([url.scheme isEqualToString:#"mailto"]) {
return YES;
}
else if ([url.scheme isEqualToString:#"tel"]) {
return YES;
}
else if (([url.scheme isEqualToString:#"http"] || [url.scheme isEqualToString:#"https"]) && [url.host isEqualToString:#"example.com"]) {
return YES;
}
return NO;
}
Then you'll need to implement the shouldOpenInSafari: method. The openURL: method can also handle tel: and mailto: links.
Some code from here.

For the urls which you want to open in web view, use the same code which you have.
For opening in safari, use this
NSString* launchUrl = #"URL to open in safari";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: launchUrl]];

Related

iOS webview load another url with Safari

I am making an app for iOS, use UIwebview to load my website in the app. I want all links (besides my website) open in Safari. Read many articles and tried many different suggestion still can't make it.
I am not familiar in coding, use Xcode 6.3.2
Here is my code of ViewController.m:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *fullURL = #"http://www.mywebsite.com";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_viewWeb loadRequest:requestObj];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
// Check if this was a click event and then some other criteria for determining if you want to launch Safari.
if (navigationType == UIWebViewNavigationTypeLinkClicked
&& [ [ request.URL scheme ] isEqualToString: #"http" ] ) {
[[UIApplication sharedApplication] openURL:request.URL];
// Return false to indicate to the UIWebView to not navigate to the linked target
return false;
}
// Return true so that the UIWebView loads the link target
return true;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
please help
Update your method
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
in something like:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *requestURL = [[request URL] absoluteString];
if ([requestURL rangeOfString:#"mydomain.com"].location != NSNotFound) {
[[UIApplication sharedApplication] openURL:[request URL]];
return NO;
}
return YES;
}

using buttons to open webviews

Hey guys, i'm trying to make the buttons on my project to open a different webview url. I'm new to iOS programming, but i've used andriod programming. Is this possible? I've a ready created another webview view that sits in the supporting files folder.
Here is my code below
Viewcontroller.m
#import "ViewController.h"
#implementation ViewController
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
-(void)viewDidLoad
{
NSString *urlString = #"http://www.athletic-profile.com/Application";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlString];
//URL Requst Object
NSURLRequest *webRequest = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webView loadRequest:webRequest];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#synthesize webView;
#end
Add a button to your View then give a connection to it. In the action method just write your code
-(IBAction*)yourButtonActionMethod:(id)sender
{
[UIWebView *aWebView =[[UIWebView alloc] initWithFrame:CGRectMake(x,y,width,height)];
aWebView.delegate=nil;
NSString *urlString = #"http://www.athletic-profile.com/Application";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlString];
//URL Requst Object
NSURLRequest *webRequest = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[aWebView loadRequest:webRequest];
[self.view addSubView:aWebView];
}
Firstly you can drag & drop UIButton in First Class & create action of that Button then create a new class for UIWebView in which you want to open you url named your choice which is subclass of UIViewController then into your .Xib or Storyboard you just drag & drop the UIWebView then create outlet of UIWebView after you write this code in first class of that button's action :-
- (IBAction *) firstButton:(id) sender
{
NSString *urlString = #"http://www.athletic-profile.com/Application";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlString];
//URL Request Object
NSURLRequest *webRequest = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webView loadRequest:webRequest];
}

No visible #interface for 'forum' declares the selector 'backToLastPage'

So am very new to xCode and it would help if someone could help me with this!
I'm creating an app that is very simple for the most part. I have a UIWebView taking me to a mobile page. This page has a log-in for Facebook. The original problem I've been having, is that since it's a mobile site I am getting a blank screen after the login is complete. I need the UIWebView to take me back to the original sign I clicked log-in at. I have copied some code which I think will work, but I I'm getting at error that says
"No visible #interface for 'forum' declares the selector 'backToLastPage'"
Could someone please tell me what I need to do to fix this problem? It's probably something simple but I need some help.
#import "forum.h"
#import "ViewController.h"
#interface forum ()
#end
#implementation forum
-(IBAction)switchback:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *myURL = [NSURL URLWithString:#"http://www.moot.it/yopyipcommunity"];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myURL];
[myWebView loadRequest:myRequest];
}
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
NSString *url = [[request URL] absoluteString];
//when user status == connected
//(has a access_token at facebook oauth response)
if([url hasPrefix:#"https://m.facebook.com/dialog/oauth"] &&
[url rangeOfString:#"access_token="].location != NSNotFound)
{
[self backToLastPage];
return NO;
}
return YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *url = [[webView.request URL] absoluteString];
if([url hasPrefix:#"https://m.facebook.com/dialog/oauth"])
{
NSString *bodyHTML =
[webView stringByEvaluatingJavaScriptFromString:#"document.body.innerHTML"];
//Facebook oauth response dead end:
// is a blank body and a head with a script that does
//nothing. But if you got back to your last page,
// the handler of authResponseChange
//will catch a connected status
// if user did his login and auth app
if([bodyHTML isEqualToString:#""])
{
[self backToLastPage];
}
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
I think forum.h is separate class, backToLastPage method is declared in that class.
#property (nonatomic, strong) forum *forum;
You need to create allocation for that class,
self.forum = [forum alloc]init];
and you call the method like this, [self.forum backToLastPage];
instead of this, [self backToLastPage];

Using PhoneGap Cleaver in iOS to override method

I am using PhoneGap 2.3 - Cleaver for iOS.
How can I override shouldStartLoadWithRequest, webViewDidStartLoad, webViewDidFinishLoad function?
If I add "viewController.webView.delegate = self" to viewDidLoad, the functions above can be called but the PhoneGap API cannot be invoked.
Thanks.
MyViewController.m:
- (void)viewDidLoad
{
[super viewDidLoad];
CDVViewController* viewController = [CDVViewController new];
viewController.view.frame = self.view.bounds;
//viewController.webView.delegate = self;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:landingURL]];
[viewController.webView loadRequest:request];
[self.view addSubview:viewController.view];
[self addChildViewController:viewController];
}
MyViewController.h:
#interface MyViewController : UIViewController <UIWebViewDelegate>
#end
You shouldn't override shouldStartLoadWithRequest because there is where they manage the javascript urls that call the native functions.
Or at least copy their code from the CDVViewController into your view controller and add the things you need.
example from phonegap 2.9.1
- (BOOL)webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL* url = [request URL];
/*
* Execute any commands queued with cordova.exec() on the JS side.
* The part of the URL after gap:// is irrelevant.
*/
if ([[url scheme] isEqualToString:#"gap"]) {
[_commandQueue fetchCommandsFromJs];
return NO;
}
/*
* If a URL is being loaded that's a file/http/https URL, just load it internally
*/
else if ([url isFileURL]) {
return YES;
}
/*
* If we loaded the HTML from a string, we let the app handle it
*/
else if (self.loadFromString == YES) {
self.loadFromString = NO;
return YES;
}
/*
* all tel: scheme urls we let the UIWebview handle it using the default behavior
*/
else if ([[url scheme] isEqualToString:#"tel"]) {
return YES;
}
/*
* all about: scheme urls are not handled
*/
else if ([[url scheme] isEqualToString:#"about"]) {
return NO;
}
/*
* all data: scheme urls are handled
*/
else if ([[url scheme] isEqualToString:#"data"]) {
return YES;
}
/*
* Handle all other types of urls (tel:, sms:), and requests to load a url in the main webview.
*/
else {
if ([self.whitelist schemeIsAllowed:[url scheme]]) {
return [self.whitelist URLIsAllowed:url];
} else {
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
} else { // handle any custom schemes to plugins
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];
}
}
return NO;
}
return YES;
}
the if ([[url scheme] isEqualToString:#"gap"]) manages phonegap calls
BTW, you shouldn't use phonegap 2.3, you need at least 2.5 to pass apple store guidelines added in may, versions previous to 2.5 used the UDID and it's forbidden by apple

UIWebView Launch in Safari

I know that this has been brought up many a times and answered twice as many on this site, however I think I may have something a little different and need to know if it is possible.
I am trying to load a banner ad from a website into a UIWebView in the app. All of this works flawlessly. However no matter what code I have tried to implement I cannot get it so that when the ad is clicked in the app it will launch in safari.
Basically I am wanting to have my own Ad server. The ad is managed ad hosted on our site. The banner has the link embedded into it by the server.
Here is the code I am using.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *string;
string = #"http://www.samplesite.com/mobile_ads";
NSURL *url = [NSURL URLWithString: string];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[self.adBox loadRequest:requestObj];
}
-(BOOL) adBox:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
if ( inType == UIWebViewNavigationTypeLinkClicked ) {
[[UIApplication sharedApplication] openURL:[inRequest URL]];
return NO;
}
return YES;
}
Any ideas of where I should go?
In your UIWebViewDelegate's webView:shouldStartLoadWithRequest:navigationType: method, do something like the following (assuming your ads have part of their URL identifiable):
- (void)methodThatCreatesTheWebview {
UIWebView *webview = [[UIWebView alloc] init];
webview.delegate = self;
}
// Portion of the URL that is only present on ads and not other URLs.
static NSString * const kAd = #"adSubdominOrSubDirectory";
// pragma mark - UIWebViewDelegate Methods
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
if ([request.URL.absoluteString rangeOfString:kAd] != NSNotFound) {
// Launch Safari to open ads
return [[UIApplication sharedApplication] openURL:request.URL];
} else {
// URL isn't an ad, so just load it in the webview.
return YES;
}
}

Resources