Load WebView with Variable - ios

I am trying to accomplish a very simple task of loading a WebView that has a variable. I am hoping to pass the variable from objective-c to a remote PHP file. The code I am using does not seem to work. The variable is valid, but I cannot get it to pass to the PHP file to be read by the WebView. Any help would be great!
NSString *userId = [[NSUserDefaults standardUserDefaults]
stringForKey:#"userId"];
[webViewFirst loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.website.com/page.php?userId=%#",userId]]];
Thank you very much!

Try +[NSString stringWithFormat] to build the URL string:
NSString *userId = <#whatever#>;
NSString *link = [NSString stringWithFormat:#"http://www.website.com/page.php?userId=%#", userId]
[webViewFirst loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:link]];

NSURL URLWithString does not support string formatting, so you cannot use it like you are trying to do.
What happens, instead, is that the C , operator is used, which just sequences the two expressions: #"http://www.website.com/page.php?userId=%#" and userId, and evaluates to the last one.
Use stringWithFormat to get it right:
[webViewFirst loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.website.com/page.php?userId=%#",userId]]]];

Related

NSURL set from variables

A pretty simple question i am sure, but i don't know how to go about doing such a thing. At current i $post variable 1 and variable 2 to the server and return some son data this is pretty slow but it worked, then it all went down hill when i started to have execution issues on the server side. Rented server so can't change php.ini file. So i have came up with this idea as a work around.
Would it be possible to direct to my download source, if the link itself contained variables collected from my label.text rather than writing each individual link out for each group (127 to be precise). For instance variable1 would equal "hell" and variable to would equal "red" therefore my NSURL would point to www.test.com/hell/red.php
Is this possible or is there some other way of doing this?
NSURL *url = [NSURL URLWithString:#"http://www.test.com/$variable1/$variable2.php"];
So now i know that this is possible, is some form or way, how can i resolve the following errors that i am receiving? For what i understand i simply can't have a / between the two variables and i can't have the .json file extension included on the end of the url.
If you require anymore code don't hesitate to ask.
Thank you very much in advance for any help!
The string you are creating the NSURL with is a normal NSString. To use variables in a NSString, you can use:
[NSString stringWithFormat:#"http://www.test.com/%#/%#.php", variable1, variable2];
%# is a placeholder for a string. variable1 and variable2 must be NSStrings
The line that creates could look like this:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.test.com/%#/%#.php", variable1, variable2]];
Or:
NSString * urlString = [NSString stringWithFormat:#"http://www.test.com/%#/%#.php", variable1, variable2];
NSURL * url = [NSURL URLWithString:urlString];
You can try this one:
NSString *urlString = [NSString stringWithFormat:#"http://www.test.com/%#/%#.php", var1, var2];
NSURL *url = [NSURL URLWithString:urlString];

webView does not load the page

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];

NSURL URLWithString returns nil

I am stuck in a very obvious method of NSURL class URLWithString I am passing a string and while creating URL it returns nil, my string is perfect. When ever I uses same string in browser then it is working fine. I am using following method to convert NSString to NSURL:
NSURL *url = [NSURL URLWithString:urlString];
//urlString is my perfect string
I have also tried to encode my string first by using following
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// using this line my output string when I log url is "url%10%10%10%10%10%10..."
%10 becomes the suffix of my url with around 100+ repetition.
If any one has idea what %10 is or what can be done to overcome this problem.
here is my urlString:
Use below code to resolve your problem.
NSString *str = msgDetail[#"thumbnail"];
NSString* webStringURL = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSURL* url = [NSURL URLWithString:webStringURL];
yes what was wrong in my string were many unidentified characters due to copying from internet site, if anyone of the reader facing this issue can copy and paste your string as see the count. And confirm.
Thanks
Try below solution
NSURL *url = [NSURL URLWithString:[urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Check it..!

UIWebView and search query

I've start to learning UIWebView and I have next problem. When I'm trying to use next code:
NSString *searchString = [NSString stringWithFormat:#"http://www.google.com/search?q=%#",lookedCity];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:searchString]]];
or:
NSString *searchString = [NSString stringWithFormat:#"http://en.wikipedia.org/wiki/%#",lookedCity];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:searchString]]];
my WebView doesn't loading page. But if I use standart URLs (ex. google.com), all works fine.
In case with Wiki, I tried use WikiApiObjectiveC, but even example doesn't work. How can I solve this problem? The best solution will be with Wiki URL.
Problem solved!
The reason, why my URL doesn't work, was in cyrillic symbols in my searchString. Solution: urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

iOS: WebView Loading a url

I am trying to open the following url in UIWebView but it fails to load whereas changing it to:
http://www.google.com
works fine.
The url that I want to load is:
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#%#%#%#",#"http://m.forrent.com/search.php?address=",[[bookListing objectForKey:#"Data"] objectForKey:#"zip"],#"&beds=&baths=&price_to=0#{\"lat\":\"0\",\"lon\":\"0\",\"distance\":\"25\",\"seed\":\"1622727896\",\"is_sort_default\":\"1\",\"sort_by\":\"\",\"page\":\"1\",\"startIndex\":\"0\",\"address\":\"",[[bookListing objectForKey:#"Data"] objectForKey:#"zip"],#"\",\"beds\":\"\",\"baths\":\"\",\"price_to\":\"0\"}"]]]];
UPDATE:
I have purposely escaped the double quotes otherwise it gives me an error.
I checked the url by opening in my browser (on laptop) and it works perfectly fine:
The url in browser:
http://m.forrent.com/search.php?address=92115&beds=&baths=&price_to=0#{%22lat%22:%220%22,%22lon%22:%220%22,%22distance%22:%2225%22,%22seed%22:%221622727896%22,%22is_sort_default%22:%221%22,%22sort_by%22:%22%22,%22page%22:%221%22,%22startIndex%22:%220%22,%22address%22:%2292115%22,%22beds%22:%22%22,%22baths%22:%22%22,%22price_to%22:%220%22}
Your line of code looks convoluted, but basically it is a very simple one.
You should breakup this code from a one liner to multiple lines that are more readable.
That will also allow you to log and check the URL you actually created, like so:
NSLog(#"My url: %#", urlString);
Update:
I see you added the full url. Webview indeed fails to load that url (UIWebkit error 101).
The part of the url that causes the problem is the '#' character and dictionary that follows in the params. You should url encode that part of the url.
Try this:
NSString *address = #"http://m.forrent.com/search.php?";
NSString *params1 = #"address=92115&beds=&baths=&price_to=0";
// URL encode the problematic part of the url.
NSString *params2 = #"#{%22lat%22:%220%22,%22lon%22:%220%22,%22distance%22:%2225%22,%22seed%22:%221622727896%22,%22is_sort_default%22:%221%22,%22sort_by%22:%22%22,%22page%22:%221%22,%22startIndex%22:%220%22,%22address%22:%2292115%22,%22beds%22:%22%22,%22baths%22:%22%22,%22price_to%22:%220%22}";
params2 = [self escape:params2];
// Build the url and loadRequest
NSString *urlString = [NSString stringWithFormat:#"%#%#%#",address,params1,params2];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
The escaping method I used:
- (NSString *)escape:(NSString *)text
{
return (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(__bridge CFStringRef)text, NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8);
}
I would try encoding all of the key/value items in your url. Specifically the curly braces ({}) and the hash (#) symbols may be causing a problem.

Resources