I am storing website addresses from users in regular NSStrings.
Some are given as "www.somewebsite.com" and some as "http://somewebsiteothersite.org".
My app should open a UIWebView and open that webpage:
NSURLRequest *requestObj = [NSURLRequest requestWithURL:[NSURL URLWithString:[self websiteString]]];
NSLog(#"visiting: %#",websiteString);
[webView loadRequest:requestObj];
But what happens is that if the http:// is omitted, the UIWebView won't open the page.
Is there a descent way to build the NSURL correctly for UIWebView?
Thanks!
Just add http:// if it's not there?
if (![urlStr hasPrefix:#"http://"] && ![urlStr hasPrefix:#"https://"]) {
urlStr = [#"http://" stringByAppendingString:urlStr];
}
beware of links that are intended to not have http:// for example ftp:// or mailto:
I know Mathiass answered quicker but I want to share a similar solution
//first detect if your string has contains http:// if not add http:// to your string
NSMutableString *websiteString = #"www.x.com";
if ([websiteString rangeOfString:#"http://"].location == NSNotFound) {
NSLog(#"contains http:// == false");
websiteString = [#"http://" stringByAppendingString:websiteString];
} else {
NSLog(#"contains http:// == true");
}
NSURLRequest *requestObj = [NSURLRequest requestWithURL:[NSURL URLWithString:[self websiteString]]];
NSLog(#"visiting: %#",websiteString);
[webView loadRequest:requestObj];
Related
I FOUND THE PROBLEM... I found that the value of berria1 have "\n " at the end of the url. where he not get this but that's the problem.
I pass very curious thing and which do not find any explanation.
The fact is that in the application, I'm parsing some news and save these in CoreData, then show a list of news in a UITableView and if I click on one of them brings me to a UIWebView in which position the link with the full story. Now comes the weird ...
If I pass to NSURL the variable which I recovery of CoreData which contains the Web address, do not load, if I pass the same direction to a NSString and this NSString to UIWebView, the UIWebView load this normally. The following is my code.
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
self.webView.delegate = self;
NSString *berria1 = [[NSString alloc]init];
berria1 = [NSString stringWithFormat:#"%#",self.abisua.noticia];
NSString *berria2 = #"http://www.vitoria-gasteiz.org/we001/was/we001Action.do?idioma=eu&aplicacion=wb021&tabla=contenido&uid=u_47906a5c_14eabe80aeb__7fe9";
NSURL *url = [NSURL URLWithString:berria1];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:urlRequest];
NSLog(#"El contenido de la noticia 1 es %#", berria1);
NSLog(#"El contenido de la noticia 2 es %#", berria2);
}
With the NSLog I see that the values of the variables are the same as you see in the picture below.
The value of the two variables in the NSLog
Image - Debug window - URL is nil
That could be happening?
Thank you.
Its not berria1 which holds the URL its berria2.
NSURL *url = [NSURL URLWithString:berria2];
Here you go give it a try the site is pretty slow so it takes a time to load
NSString *berria2 = #"http://www.vitoria-gasteiz.org/we001/was/we001Action.do?%20%20%20%20idioma=eu&aplicacion=wb021&tabla=contenido&uid=u_47906a5c_14eabe80aeb__7fe9";
NSURL *myUrl = [NSURL URLWithString:berria2];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myUrl];
[self.webView loadRequest:myRequest];
Try this. I didn't see any code how you load the request to webview. But I added the code with that part. Replace it with your webview.
NSString *myurlString = [NSString stringWithFormat:#"%#",self.abisua.noticia];
NSString *cleanedUrl = [myurlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSURL *myUrl = [NSURL URLWithString:cleanedUrl];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myUrl];
UIWebView *mywebview = [[UIWebView alloc] init];
[mywebview loadRequest:myRequest];
I finally found and fixed the problem.
The problem was that the variable received whith Core Data and pass to NSString, I do not know how, but the link have added this characters at the end of URL "\n "
Berria1 variable value in debug area was:
berria1 __NSCFString * #"http://www.vitoria-gasteiz.org/we001/was/we001Action.do?idioma=eu&aplicacion=wb021&tabla=contenido&uid=u_47906a5c_14eabe80aeb__7fe9\n " 0x0000000126d9e6c0
Then when I passed this value to NSURL and this found these characters, NSURL value pass to nil.
Then I solved this, passing this NSString to a NSMutableString and erasing these characters before pass to NSURL with this code:
NSString *berria1 = self.abisua.noticia;
NSMutableString * miCadena = [NSMutableString stringWithString: berria1];
[miCadena deleteCharactersInRange: [miCadena rangeOfString: #"\n "]];
Thanks everyone for your help
hi am new to iOS developer,i have seen your code in that your adding second string to url why still understand just try adding 2nd string
NSURL *url = [NSURL URLWithString:berria2];
I have a UIWebView where i load a url. But it does not load full content. I have checked all possible forums for solution but couldn't find a breakthrough yet. Any help would be really appreciated? You can try out the below url yourself. Basically, the url is supposed to contain html5 content/player.
-(void)loadPlayerUrl
{
activityIndicatorView.hidden = NO;
NSURL* nsUrl = [NSURL URLWithString:#"http://watch.nimbletv.com/tv"]
NSURLRequest* request = [NSURLRequest requestWithURL:nsUrl cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30];
[self.playerWebView loadRequest:request];
}
However, this works perfectly in safari or any other browser.
You should create ViewControllerWebPage
Then
- (void)viewDidLoad
{
[super viewDidLoad];
self.screenName = #"Info Ekran";
NSURL *mobileCreaURL = [NSURL URLWithString:#"http://mobilecrea.com/"];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:mobileCreaURL];
[mobileCrea loadRequest:myRequest];
}
Also create new view, select your new custom class (ViewControllerWebPage) and than create UIWebView
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.
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]
}
}
I thought it would be easy to load in a html file from my resources into a UIWebView, but it looks like it requires something extra that I'm not doing. So far I have in my viewDidLoad in my controller:
NSURL *url = [NSURL URLWithString:#"radialGradient.html"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[webView loadRequest:req];
webView.frame = CGRectMake(0, 0, 768, 1024);
I've tried regular web addresses (google.com) and it works fine. But with the file in my sources it just renders a white blank screen.
Two things:
1)
What you have now is not a URL. It's just a filename. You need to be prepending a "file:///" in front of that radialGradient.html.
2)
And, you'll likely also need to put in a resolvable path to radialGradient.html Right now your app doesn't know where to look for it.
Something like:
NSURL * resourcePathURL = [[NSBundle mainBundle] resourceURL];
if(resourcePathURL)
{
NSURL * urlToLoad = [resourcePathURL URLByAppendingPathComponent: #"radialGradient.html"];
if(urlToLoad)
{
NSURLRequest * req = [NSURLRequest requestWithURL: urlToLoad];
[webView loadRequest: req];
}
}