Encoding for getting contents of a url IOS - ios

I want to get the contents of a url hosted by me. The contents of the url is
<p class="citation_style_APA">Blaine, J. D. (1992). <i>Buprenorphine: An alternative treatment for opioid dependence</i>. Rockville, MD: U.S. Dept. of Health and Human Services, Public Health Service, Alcohol, Drug Abuse, and Mental Health Administration, National Institute on Drug Abuse. </p>
Below is my code to get the above contents in a string.
NSString *s =[NSString stringWithFormat:#"%#",#"xyz.com"];
url = [NSURL URLWithString:s];
NSString *content = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:nil];
NSLog(#"%#",content);
I am getting null, can anyone tell where i am going wrong.

Try a complete web address, like #"http://www.xyz.com/myfile.html". Once you get it working, you'll want to change to an asynch technique.

You need to do two things.
1. you should use a valid url
2. NSString *content=[[NSString string] initWithContentsOfURL:url encoding:NSASCIIStringEncoding error:Nil];
Now check your Log; It'll definitely work.

Try this way
NSString *strUrl = < YOUR URL >
NSURL *url = [NSURL URLWithString:[strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError *error = nil;
NSString *content = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
if(content==nil)
NSLog(#"%#",error!=nil ? error.description : #"");
else
NSLog(#"%#",content);

Related

NSURL with JSON returns null

I'm keep getting a (null) error when I try to build my NSURL to open another app.
The URL should be
ms-test-app://eventSourceId=evtSrcId&eventID=13675016&eventType=0&json={"meterresults":[{"clean":"2","raw":"2","status":"0"}]}
but when I try to build my URL it's always null.
At first I thought it has something to do with the URL itself, but it's the same as I got it from the example here.
Another thought was that IOS got some problems with the double quotes in the JSON, but I replaced them with %22, but this doesn't work either.
Here is the code, where I build the URL:
NSString *jsonString = [NSString stringWithFormat:#"{%22meterresults%22:[{%22clean%22:%22%#%22,%22raw%22:%22%#%22,%22status%22:%22%#%22}]}", cleanReadingString, rawReadingString, status];
NSLog(#"JSON= %#",jsonString);
//Send the result JSON back to the movilizer app
NSString *eventSourceId = #"evtSrcId";
NSString *encodedQueryString = [NSString stringWithFormat:#"?eventSourceId=%#&eventID=%d&eventType=0&json=%#",
eventSourceId, _eventId, jsonString];[NSCharacterSet URLQueryAllowedCharacterSet]]
NSString *urlStr = [NSString stringWithFormat:#"%#%#",
[_endpointUrls objectForKey:[NSNumber numberWithInt:(int)_selectedEndpoint]],
encodedQueryString];
NSURL *url = [NSURL URLWithString:urlStr];
I don't know where I'm wrong and I would be glad if someone got any idea.
Thanks in advance.
You should really be using NSURLComponents to create URLs rather than trying to format them into a string.
NSDictionary* jsonDict = #{#"clean": #"2", #"raw": #"2", #"status": #"0"};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:NULL];
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSURLComponents* components = [[NSURLComponents alloc] init];
components.scheme = #"ms-test-app";
components.queryItems = #[
[[NSURLQueryItem alloc] initWithName:#"eventSourceId" value:eventSourceId],
[[NSURLQueryItem alloc] initWithName:#"eventID" value:#(_eventId).stringValue],
[[NSURLQueryItem alloc] initWithName:#"json" value:jsonString]
];
NSURL* url = components.URL;
Once you build the URL that way, it becomes apparent that your string doesn't have a host portion (or more accurately, one of your parameters is being used as the host portion).
The other comments about not being able to send JSON as an URL parameter are incorrect. As long as the system on the other side that is parsing the query string can handle it, you can send anything you want as an URL parameter.

How can I guess the two letter language code for a Google suggestions feature?

I've implemented a very simple Google suggestions feature based on what I've found here: http://shreyaschand.com/blog/2013/01/03/google-autocomplete-api/
You don't even have to use an XML parser:
+ (NSArray *)suggestionsForQuery:(NSString *)query language:(NSString *)language
{
NSMutableArray *suggestions;
NSString *URLString = [NSString stringWithFormat:#"http://suggestqueries.google.com/complete/search?q=%#&client=toolbar&hl=%#", query, language];
NSError *error = nil;
NSString *XMLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:URLString] encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"ERROR {%#}", error.description);
}
else {
XMLString = [XMLString stringByReplacingOccurrencesOfString:#"<?xml version=\"1.0\"?>" withString:#""];
XMLString = [XMLString stringByReplacingOccurrencesOfString:#"<toplevel>" withString:#""];
XMLString = [XMLString stringByReplacingOccurrencesOfString:#"</toplevel>" withString:#""];
XMLString = [XMLString stringByReplacingOccurrencesOfString:#"<CompleteSuggestion>" withString:#""];
XMLString = [XMLString stringByReplacingOccurrencesOfString:#"</CompleteSuggestion>" withString:#""];
XMLString = [XMLString stringByReplacingOccurrencesOfString:#"<suggestion data=\"" withString:#""];
suggestions = [NSMutableArray arrayWithArray:[XMLString componentsSeparatedByString:#"\"/>"]];
[suggestions removeLastObject];
}
return suggestions;
}
It works but only if you already know the two letter language code.
Do you know of any way in which I can guess the two letter language code based on the location the user is searching from?
If it's strictly based on location, I wouldn't like it if let's say a user has gone on vacation in France and all of a sudden suggestions change to Google France.
Should it be based on what language the user is already using on his iOS device?
This correction will actually solve the problem:
NSString *URLString = [NSString stringWithFormat:#"http://suggestqueries.google.com/complete/search?q=%#&client=toolbar&hl=%#", query, [[NSLocale currentLocale] languageCode]];
Still, people living in India and having their language set to French will have Google suggestions based on Google France.
This is more like lessening the weight of the problem than solving it.

Extract vimeo video Id from vimeo url objective-c

I want to extract video id from a vimeo url, can any body help me with the RegEx for the same.
Video url can be of type
https://vimeo.com/173652088
this is just a sample url. RegEx should work for all vimeo urls.
plz try this code
NSString *yourStr = #"https://vimeo.com/173652088";
NSString *str = [yourStr stringByReplacingOccurrencesOfString: #"https://" withString:#""];
NSArray *arryVedios =[str componentsSeparatedByString:#"/"] ;
NSString *id= [ arryVedios lastObject];
NSLog(#"id= %#",id);
this code work for every url.but your id must be in last.
NSString *old = #"https://vimeo.com/173652088";
NSString *new = [old stringByReplacingOccurrencesOfString: #"https://vimeo.com/" withString:#""];
NSLog(#"new= %#", new);
NSString *newone = [[old componentsSeparatedByString:#"/"] lastObject];
NSLog(#"newone= %#", newone);
If you are sure it is a vimeo url then the following would work
[^\/]+(?=\/$|$)
online tester here
online regex tester
Also you can extract the lastComponent from the Url
NSURL* url = [NSURL URLWithString:#"https://vimeo.com/173031270"];
NSLog(#video id: %#", url.lastPathComponent);
Note that this solution will fail if you have a url like "https://vimeo.com/173031270?a=1&b=2"

How do I add a number to an NSURL? Too many arguments error

I've got a small problem that seems a little bit odd to me. I often used NSString or NSLog while adding NSNumbers into several places:
NSNumber *categoryId = [[NSNumber alloc]initWithInt:0];
NSURL *url = [NSURL URLWithString:#"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]];
Now xcode tells me that I'm too many arguments. What am I doing wrong? Setting up an NSNumber into NSStrings or NSLogs works as I did it above.
Best Regards
What is wrong is on
NSURL *url = [NSURL URLWithString:#"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]];
you are calling URLWithString: and then pass in a string that is not being formatted correctly. If you want to do it all on one line then you need to be using stringWithFormat: like
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]]];
Because it is adding a parameter you can't just create a string like you normally would with #"some text" you need to format it using the stringWithFormat: which will return an NSString * with the text held within #"" and the paramters you pass in. So [NSString stringWithFormat:#"My String will come with %#", #"Apples"]; this would provide an NSString with "My String will come with Apples". For more information check out the Apple Documentation for NSString and stringWithFormat:
Try this :
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://shop.rs/api/json.phpaction=getCategoryByCategory&category=%i", [categoryId integerValue]]];
Initially code was wrong because of : "categoryId integerValue]" (I forgot a '[').
You can use NSString to form your NSURL. You can then pass it to your URLWithString like below:
NSNumber *categoryId = [NSNumber numberWithInteger:0];
NSString *urlString = [NSString stringWithFormat:#"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]];
NSURL *url = [NSURL URLWithString:urlString];

Objective C get html from URL, encoding wrong

I want to ge the html content from the url bellow:
https://bbs.sjtu.edu.cn/file/bbs/mobile/top100.html
The code I have use below:
NSURL *url2 = [NSURL URLWithString:#"http://bbs.sjtu.edu.cn/file/bbs/mobile/top100.html"];
NSString *res = [NSString stringWithContentsOfURL:url2 encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000) error:nil];
NSLog(#"%#",res);
the result is null.
I have also tried with UTF8 encoding (also null) and ASCII encoding (has content and the english part of the content is right, but for Chinese charset, the content is garbled).
any one can help about this problem? I have been stuck here for a lot of time.
Try using stringWithContentsOfURL:usedEncoding:error: instead:
NSError *error = nil;
NSStringEncoding encoding;
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url2
usedEncoding:&encoding
error:&error];

Resources