iOS: WebView Loading a url - ios

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.

Related

iPhone QR code customize

I want to use customize QR, I have a url, if I pass that url in browser they display a QR in browser and if i use this url in our code they return null, this is my url that I want to use in our code:
http://api.qrcode.unitag.fr/api?t_pwd=degraded&setting={"EYES":{"EYE_TYPE":"LLLeft","COLOR_EHD":"8a9935","COLOR_IHD":"8a9935","COLOR_EBG":"71801f","COLOR_IBG":"71801f"},"BODY_TYPE":2,"LAYOUT":{"COLORBG":"ffffff","GRADIENT_TYPE":"HORI","COLOR1":"afc928","COLOR2":"d7eb67","FORCE_SHADOW":"L","COLOR_SHADOW":"b6b8a7"}}&data={"DATA":{"MESSAGE":"Hello","PHONE":"0505050505"},"TYPE":"smsto"}
This is my code for encode that url
NSString *unescaped = #"http://api.qrcode.unitag.fr/api?t_pwd=degraded&setting={%22EYES%22:{%22EYE_TYPE%22:%22LLLeft%22,%22COLOR_EHD%22:%228a9935%22,%22COLOR_IHD%22:%228a9935%22,%22COLOR_EBG%22:%2271801f%22,%22COLOR_IBG%22:%2271801f%22},%22BODY_TYPE%22:2,%22LAYOUT%22:{%22COLORBG%22:%22ffffff%22,%22GRADIENT_TYPE%22:%22HORI%22,%22COLOR1%22:%22afc928%22,%22COLOR2%22:%22d7eb67%22,%22FORCE_SHADOW%22:%22L%22,%22COLOR_SHADOW%22:%22b6b8a7%22}}&data={%22DATA%22:{%22MESSAGE%22:%22Hello%22,%22PHONE%22:%220505050505%22},%22TYPE%22:%22smsto%22}";
NSString *escapedString = [unescaped stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSLog(#"escapedString: %#", escapedString);
NSURL *url = [NSURL URLWithString:escapedString];
[img_barcode setImageWithURL:url placeholderImage:nil];
i am using above code but i am not getting image, please tell me about this process how i can get image successfully.
The URL in your code is already escaped. By escaping it again, you destroy it.
Either start with a properly URL escaped string and don't do any further processing on it:
NSString *escaped = #"http://api.qrcode.unitag.fr/api?t_pwd=degraded&setting={%22EYES%22{%22EYE_TYPE%22:%22LLLeft%22,%22COLOR_EHD%22:%228a9935%22,%22COLOR_IHD%22:%228a9935%22,%22COLOR_EBG%22:%2271801f%22,%22COLOR_IBG%22:%2271801f%22},%22BODY_TYPE%22:2,%22LAYOUT%22{%22COLORBG%22:%22ffffff%22,%22GRADIENT_TYPE%22:%22HORI%22,%22COLOR1%22:%22afc928%22,%22COLOR2%22:%22d7eb67%22,%22FORCE_SHADOW%22:%22L%22,%22COLOR_SHADOW%22:%22b6b8a7%22}}&data={%22DATA%22{%22MESSAGE%22:%22Hello%22,%22PHONE%22:%220505050505%22},%22TYPE%22:%22smsto%22}";
Or start with the base url and the parameters, then URL escape each parameter value and combine it into the complete URL:
Base URL: http://api.qrcode.unitag.fr/api
t_pwd: degraded
setting: {"EYES":{"EYE_TYPE":"LLLeft","COLOR_EHD":"8a9935","COLOR_IHD":"8a9935","COLOR_EBG":"71801f","COLOR_IBG":"71801f"},"BODY_TYPE":2,"LAYOUT":{"COLORBG":"ffffff","GRADIENT_TYPE":"HORI","COLOR1":"afc928","COLOR2":"d7eb67","FORCE_SHADOW":"L","COLOR_SHADOW":"b6b8a7"}}
data: {"DATA":{"MESSAGE":"Hello","PHONE":"0505050505"},"TYPE":"smsto"}
So the easiest solution is probably to remove the code lines that run the URL encoding.
Finally i solved the problem thank every one.
that was my url:
http://api.qrcode.unitag.fr/api?t_pwd=degraded&setting={"EYES":{"EYE_TYPE":"LLLeft","COLOR_EHD":"8a9935","COLOR_IHD":"8a9935","COLOR_EBG":"71801f","COLOR_IBG":"71801f"},"BODY_TYPE":2,"LAYOUT":{"COLORBG":"ffffff","GRADIENT_TYPE":"HORI","COLOR1":"afc928","COLOR2":"d7eb67","FORCE_SHADOW":"L","COLOR_SHADOW":"b6b8a7"}}&data={"DATA":{"MESSAGE":"Hello","PHONE":"0505050505"},"TYPE":"smsto"}
and i just added back slash before the (") (") like this \"EYES\", and after that i use this line of code:
NSString *escapedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding];
NSURL * imageURL = [NSURL URLWithString:escapedUrlString];
[img_barcode setImageWithURL:imageURL placeholderImage:nil];
and my problem is solved.

Initializing NSAttributedString with HTML file parses HTTP links as file URLs

iOS 7 allows an NSAttributedString to be initialized with an HTML file or data. I want to use this functionality to make it easier to insert links in 'About' texts of apps.
To achieve this, I initialize the NSAttributedString with the following code:
NSURL *url = [[NSBundle mainBundle] URLForResource:#"test.html" withExtension:nil];
NSError *error = nil;
NSDictionary *options = nil;
NSDictionary *attributes = nil;
_textView.attributedText = [[NSAttributedString alloc] initWithFileURL:url options:options documentAttributes:&attributes error:&error];
and a file with the following content:
<html><body>
<p>This is a test link. It leads to StackOverflow.<p>
</body></html>
Update
The above HTML still had the escape marks from trying to use it in code as an NSString. Removing the escapes makes it work just fine. Also answered my own question below.
End update
This works fine, and gives a string with the url properly formatted and clickable. Clicking the link calls the UITextView's delegate -textView:shouldInteractWithURL:inRange: method. However, inspecting the URL parameter shows the URL actually has the following absolute string:
file:///%22http://www.google.com/%22
which obviously doesn't open the appropriate webpage. I don't find the documentation on NSAttributedText clear enough to determine why this happens.
Anyone know how I should initialize the NSAttributedString to generate the appropriate URL?
Try reading the HTML file into a NSString and then use:
NSString *path = [[NSBundle mainBundle] pathForResource:#"test.html" ofType:nil];
NSString *html = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
_textView.attributedText = [[NSAttributedString alloc] initWithHTML:html baseURL:nil options:options documentAttributes:&attributes];
At least this should work if it is similar with what happens in UIWebViews. The URL is resolved using the baseURL. It appears that in your code the source url is also used as baseURL. So I am passing a nil URL to prevent resolving against a local file URL.
The answer to this question is that the HTML file was invalid.
Having copy/pasted the html directly from a string defined in Objective-C, I forgot to remove the escapes before each quote. This of course translated directly to a file url instead of an HTML url. Removing the escape marks fixes this.

How do I strip the query (used for GET parameters) from a URL?

I'm building a small REST service to authorize users into my app.
At one point, the UIWebView I'm using to authorize the user, will go to https://myautholink.com/login.php. This page sends a JSON response with an authorization token. The thing about this page is that it receives some data via GET via my authorization form. I cannot use PHP sessions because you arrive to this page via:
header("location:https://myautholink.com/login.php?user_id=1&machine_id=machine_id&machine_name=machine_name&app_id=app_id");
Since the header function sends in headers, I cannot do a session_start(); at the same time.
I can get the UIWebView's request URL without a problem using the delegate methods:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSURLRequest *request = [webView request];
NSLog(#"%#", [[request URL] relativeString]);
if([[[request URL] absoluteString] isEqualToString:SPAtajosLoginLink])
{
//Store auth token and dismiss auth web view.
}
}
The thing is none of the NSURL methods seem to return the "clean" link without the parameters. I have looked at all the NSURL url-string related methods:
- (NSString *)absoluteString;
- (NSString *)relativeString; // The relative portion of a URL. If baseURL is nil, or if the receiver is itself absolute, this is the same as absoluteString
But absoluteString is always the full URL with the GET parameters and relativeString is always nil.
I'm scratching my head with this and I can't seem to find the solution. Any help will be appreciated.
Rather than mess about with your own string manipulation, hand off to NSURLComponents:
NSURLComponents *components = [NSURLComponents componentsWithURL:url];
components.query = nil; // remove the query
components.fragments = nil; // probably want to strip this too for good measure
url = [components URL];
On iOS 6 and earlier, you can bring in KSURLComponents to achieve the same result.
Example: http://www.google.com:80/a/b/c;params?m=n&o=p#fragment
Use these methods of NSURL:
scheme: http
host: www.google.com
port: 80
path: /a/b/c
relativePath: /a/b/c
parameterString: params
query: m=n&o=p
fragment: fragment
Or, in iOS 7, build a NSURLComponents instance, then use the methods scheme, user, password, host, port, path, query, fragment, to extract part of the URL as strings. Then build the base URL back.
NSString* baseURLString = [NSString stringWithFormat:#"%#://%#/%#", URL.scheme, ...
NSURL *baseURL = [NSURL URLWithString:baseURLString];
To update this answer for iOS 7 onwards:
NSURLComponents *components = [NSURLComponents componentsWithURL: url resolvingAgainstBaseURL: NO];
components.query = nil; // remove the query
components.fragment = nil; // probably want to strip this too for good measure
url = [components URL];
Please note also that there is no 'fragments' property. It's just 'fragment'.
Otherwise, this method is great. Much better than worrying about putting the URL back together properly with string manips.

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

Load WebView with Variable

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

Resources