I am currently using ChildBrowser in phoneapp to open a website. However, I would like to open all external links of this website to open in Safari.
I do not have control over the source of this website.
My understanding is that I have to modify ChildBrowser to open all links starting with "http" in Safari.
I can't exactly read Objective-C, but I believe the code below is relevant.
- (void)loadURL:(NSString*)url
{
NSLog(#"Opening Url : %#",url);
if( [url hasSuffix:#".png" ] ||
[url hasSuffix:#".jpg" ] ||
[url hasSuffix:#".jpeg" ] ||
[url hasSuffix:#".bmp" ] ||
[url hasSuffix:#".gif" ] )
{
[ imageURL release ];
imageURL = [url copy];
isImage = YES;
NSString* htmlText = #"<html><body style='background-color:#333;margin:0px;padding:0px;'><img style='min-height:200px;margin:0px;padding:0px;width:100%;height:auto;' alt='' src='IMGSRC'/></body></html>";
htmlText = [ htmlText stringByReplacingOccurrencesOfString:#"IMGSRC" withString:url ];
[webView loadHTMLString:htmlText baseURL:[NSURL URLWithString:#""]];
}
else if ( [url hasPrefix:#"http" ])
{
//I have added in this else if.
}
else
{
imageURL = #"";
isImage = NO;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[webView loadRequest:request];
}
webView.hidden = NO;
}
Any advice?
The easiest way I've found to do this is, if you know the Domain Host name that you will initially be requesting with childBrowser and you don't plan on requesting any other Domains then you can write this event right into the ChildBrowserViewController.m file.
- (BOOL)webView:(UIWebView *)theWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *url = [request URL];
NSString* domain = [url host];
// Intercept the external http requests and forward to Safari.app
// Otherwise forward to the PhoneGap WebView
if ([[url scheme] isEqualToString:#"http"] || [[url scheme] isEqualToString:#"https"] || [[url scheme] isEqualToString:#"www"]) {
if ( [domain isEqualToString:#"YOURDOMAIN.NAME] ) {
return YES;
} else {
[[UIApplication sharedApplication] openURL:url];
return NO;
}
} else {
return YES;// [ super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType ];
}
}
This will catch all requests made by childBrowser and if they match standard URL convention (preceding with HTTP, HTTPS, or WWW) and they are not your Domain Host name that you preset then it will foce them to open in Safari. Then when the user returns to your app they will still be on the previous page they where when they clicked the link.
I messed with this for hours until I came up with this.
If you need to be able to open more than one Domain Host with childBrowser but still want each one to open all external links leading away from that current domain in Safari I would suggest the following.
Add the following to ChildBrowserViewController.h
BOOL scaleEnabled;
BOOL isImage;
NSString* originalURL; <- THIS RIGHT HERE
NSString* imageURL;
And this
#property(retain) NSString* imageURL;
#property(retain) NSString* originalURL; <- THIS RIGHT HERE
#property(assign) BOOL isImage;
Then add the following to ChildBrowserViewController.m
#synthesize imageURL;
#originalURL; <- THIS RIGHT HERE
#synthesize supportedOrientations;
#synthesize isImage;
And add the following
- (void)loadURL:(NSString*)url
{
originalURL = url; <- THIS RIGHT HERE
NSLog(#"Opening Url : %#",url);
And then in the method I posted above change the following
NSURL *url = [request URL];
NSString* domain = [url host];
NSURL *oURL = [NSURL URLWithString: originalURL]; <- THIS RIGHT HERE
NSString* oDomain = [oURL host]; <- THIS RIGHT HERE
// Intercept the external http requests and forward to Safari.app
// Otherwise forward to the PhoneGap WebView
if ([[url scheme] isEqualToString:#"http"] || [[url scheme] isEqualToString:#"https"] || [[url scheme] isEqualToString:#"www"]) {
if ( [domain isEqualToString:oDomain] ) { <- THIS RIGHT HERE
return YES;
} else {
I haven't tested this second part but it should work just fine.
Good luck.
Related
Im working on a web based application, it contains only one webView, the code below:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
if ((navigationType == UIWebViewNavigationTypeLinkClicked )) {
[[UIApplication sharedApplication] openURL:[request URL]] ;
}
HUD = [[MBProgressHUD alloc] initWithView:self.view];
[self.view addSubview:HUD];
// Set determinate mode
[HUD show:YES];
//CAPTURE USER LINK-CLICK.
NSURL *url = [request URL];
NSString *urls= [url absoluteString];
NSString *code = [urls substringFromIndex: [urls length] - 1];
if ( [urls containsString:#".html"] && ![code isEqualToString:#"#"] ) {
_webView.hidden= YES;
}
this code will open all the web views on safari , but i only need to open specific URLs on safari
for example :
http://xxxx/residential/ this must be opened on safari, while all the other pages should be opened on webView inside the application.
Any help
First thing is that you want to open specific urls that should open in Safari instead of UIWebView. But there is not any conditions that fulfill your requirement.
First check your [request url] with your desired url. If both matched then open that url in SFSafariViewController instead of openUrl function. in else conditon you can load your [request url] which you don't want to open in Safari.
NSString *testString =[NSString stringWithFormat:#" Google"];
[webView loadHTMLString:testString baseURL:nil];
I want to get the URL when I click on this UIWebView content in
-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
if ( inType == UIWebViewNavigationTypeLinkClicked ) {
[[UIApplication sharedApplication] openURL:inRequest.mainDocumentURL];
return NO;
}
return YES;
}
delegate method.
When I click google hyperlink in webview it gives
URL: applewebdata://
Please help me.
You question is not very clear if you want to get the tapped url on webview or the webview's loaded page url ,
If you want to get webview loaded page url you can use NSURLRequestObject,something like
NSString * url = [request URL];
If you want to get the clicked link url , you will have to use this java script
NSString *url = [webView stringByEvaluatingJavaScriptFromString:#"window.location"];
you can do like this way
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if ([request.URL.absoluteString rangeOfString:#"www.google.com"].location!=NSNotFound)
{
[[UIApplication sharedApplication]openURL:request.URL];
return NO;
}
return YES;
}
For Swift:
Whenever your webpage is loaded you can use this, I use it for a label in this case:
webUrlLabel.text = webView.request.URL.absoluteString
For Objective-C:
NSString *currentPage = [NSString stringWithFormat:#"%#", webView.request.URL.absoluteString];
webUrlLabel is a UILabel
webView is my UIWebView
You already have NSURLRequest object. Access url from that.
inRequest.URL
way 1:
NSString *currentURL = myWebView.request.URL.absoluteString;
Way 2:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
//CAPTURE USER LINK-CLICK.
NSURL *url = [request URL];
yourTextBox.text = [url absoluteString];
return YES;
}
Please let me know if it works. Thanks
I'm loading a remote webpage into an iOS webview which relies on js and css assets. To improve the performance particularly on 3G networks, I'm hoping to call these assets from files local to the iOS device.
The website backing the iOS app is also used by mobile phone browsers, not just the iOS app, so subclassing NSURLRequest to register my own URL prefix (myurl://) is not ideal.
I already have code that launches mobileSafari for URLs outside of my domain:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [request URL];
NSString *hostname = [url host];
if (![hostname hasSuffix:#".mysite.com"] && navigationType == UIWebViewNavigationTypeLinkClicked) {
[[UIApplication sharedApplication] openURL:url];
return NO;
}
return YES;
}
This method is called from the same controller implementation with code like this:
- (void)viewDidLoad {
[super viewDidLoad];
// ...
webView.delegate = self;
// ...
NSURL *url = [[NSURL alloc] initWithString:([path length] > 0 ? path : #"http://mysite.com/mobile/index")];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
[webView loadRequest:request];
// ...
}
I've reviewed several other questions ( How to use an iPhone webView with an external HTML that references local images? , Dynamically loading javascript files in UIWebView with local cache not working, iOS WebView remote html with local image files, Using local resources in an iPhone webview ) but they all seem to miss a key element to my problem.
The first link has the start of something promising:
if ([url isEqualToString:#"http://path-to-cdn.com/jquery-1.8.2.min.js"]) {
fileToLoad = [[NSBundle mainBundle] pathForResource:#"jquery-1.8.2.min" ofType:#"js"];
}
If that's a sensible approach, I'm stuck on how to get from passing that fileToLoad NSBundle into the webView's loadRequest, since that's expecting a URL.
I think I'm on the right path after realizing that I could use the output of stringByAppendingPathComponent as a URL, like so...
if (![hostname hasSuffix:#".mysite.com"] && navigationType == UIWebViewNavigationTypeLinkClicked) {
NSString *urlString = [url absoluteString];
if ([urlString isEqualToString:#"http://path-to-cdn.com/jquery-1.8.2.min.js"]) {
NSString *tempurl = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"js/jquery-1.8.2.min.js"];
[webView loadRequest:[NSMutableURLRequest requestWithURL:tempurl]];
} else {
[[UIApplication sharedApplication] openURL:url];
}
return NO;
}
return YES;
I don't have it working yet (it's still loading the remote URL) but I think I'm on the right path.
I am building an app in xcode using the Cordova/phonegap framework for ios which displays some html that has some embeded youtube player code in it. iOS seems to redirect the user to the youtube app when it hits this youtube player. In cordova 1.5.0 the following code worked, but in 1.6.1 it doesn't seem to. Any ideas why or what needs changing to get it to work?
code to stop youtube opening up and links to behave selves
- (BOOL)webView:(UIWebView *)theWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *url = [request URL];
// Intercept the external http requests and forward to Safari.app
// Otherwise forward to the PhoneGap WebView
NSString* urlString = [url absoluteString];
if([urlString rangeOfString:#"http://www.youtube.com/embed"].location != NSNotFound) {
return [ super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType ];
}
else if (([[url scheme] isEqualToString:#"http"] || [[url scheme] isEqualToString:#"https"])) {
[[UIApplication sharedApplication] openURL:url];
return NO;
}
else {
return [ super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType ];
}
}
I would put logging in for url at the beginning of the method, and then a log statement in each clause of the if/elseif/else so you can see what urls are being intercepted and what the method then does with each one.
Maybe the string for the youtube request doesn't match the hardcoded "http://www.youtube.com/embed" any more? Worth a look.
look at http://apiblog.youtube.com/2009/02/youtube-apis-iphone-cool-mobile-apps.html
this might help.
It says to do this:
NSString *htmlString = #"<html><head>
<meta name = \"viewport\" content = \"initial-scale = 1.0, user-scalable = no, width = 212\"/></head>
<body style=\"background:#F00;margin-top:0px;margin-left:0px\">
<div><object width=\"212\" height=\"172\">
<param name=\"movie\" value=\"http://www.youtube.com/v/oHg5SJYRHA0&f=gdata_videos&c=ytapi-my-clientID&d=nGF83uyVrg8eD4rfEkk22mDOl3qUImVMV6ramM\"></param>
<param name=\"wmode\" value=\"transparent\"></param>
<embed src=\"http://www.youtube.com/v/oHg5SJYRHA0&f=gdata_videos&c=ytapi-my-clientID&d=nGF83uyVrg8eD4rfEkk22mDOl3qUImVMV6ramM\"
type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"212\" height=\"172\"></embed>
</object></div></body></html>";
[webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:#"http://www.your-url.com"]];
Help making a Unified address bar in ios 5 for a Browser App? So here is my address bar.
-(IBAction)url:(id)sender {
NSString *query = [urlBar.text stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSURL *urlQuery = [NSURL URLWithString:[NSString stringWithFormat:#"http://%#", query]];
NSURLRequest *request = [NSURLRequest requestWithURL:urlQuery];
[webPage loadRequest:request];
}
Couldn't I add an "else" reference to say if it is not an address then append the google search tag? If so how? And would you know how to use Bing instead of google?
-(IBAction)googleSearch:(id)sender {
NSString *query = [googleSearch.text stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSURL *urlQuery = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.google.com/search?hl=en&site=&q=%#", query]];
NSURLRequest *request = [NSURLRequest requestWithURL:urlQuery];
[webPage loadRequest:request];
}
Here are some tips to help you:
use stringByAddingPercentEscapesUsingEncoding: instead of your "+" replacement.
you should check if http:// is not a prefix to the URL string before adding it
you should implement the UIWebViewDelegate protocol to identify when an error occurs when loading an invalid URL
then as a fallback launch your Google search (now you can replace " " by "+")... or Bing, whatever and up to you!
Your code should looks something as follow:
...
webView.delegate = self; // Should appear in your code somewhere
...
-(IBAction)performSearch {
if ([searchBar.text hasPrefix:#"http://"]) {
... // Make NSURL from NSString using stringByAddingPercentEscapesUsingEncoding: among other things
[webView loadRequest:...]
} else if ([self isProbablyURL:searchBar.text]) {
... // Make NSURL from NSString appending http:// and using stringByAddingPercentEscapesUsingEncoding: among other things
[webView loadRequest:...]
} else {
[self performGoogleSearchWithText:searchBar.text]
}
}
- (BOOL)isProbablyURL:(NSString *)text {
... // do something smart and return YES or NO
}
- (void)performGoogleSearchWithText:(NSString *)text {
... // Make a google request from text and mark it as not being "fallbackable" on a google search as it is already a Google Search
[webView loadRequest:...]
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
... // Notify user
if (was not already a Google Search) {
[self performGoogleSearchWithText:searchBar.text]
}
}