Objective C get html from URL, encoding wrong - ios

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

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 to use stringWithContentsOfFile:usedEncoding:error:

I've tried to load a file with unknown encoding. This is because I dont always have control over the file that I will load. I assumed that the method stringWithContentsOfFile:usedEncoding:error: will do this and will let me know the file encoding. Unfortunately following code doesn't provide the encoding I want - it always return 0.
NSStringEncoding *encoding = nil;
NSError *error = nil;
NSString *json = [NSString stringWithContentsOfFile:path
usedEncoding:encoding
error:&error];
NSLog(#"\n%lu\n%#",(unsigned long)encoding,error);
It returns content of file, so you may wonder why I need this encoding, well that string is JSON that I want to serialize it into NSDictionary and the dataUsingEncoding: method requires encoding. I tried to pass encoding variable but this throws an error. So I tried fail safe UTF8 encoding and then it worked.
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
So I must using this incorrect as encoding equals to 0 instead of 4 (UTF8). Can someone help me with that?
Try that :
NSStringEncoding encoding;
NSError *error = nil;
NSString *json = [NSString stringWithContentsOfFile:path
usedEncoding:&encoding
error:&error];
NSLog(#"\n%lu\n%#",(unsigned long)encoding,error);
To be clearer, you can't receive the encoding value in your pointer, you need to give a plain NSStringEncoding address
Since you are not aware of the encoding of the file, I will suggest you to see this link.
Its basically String Programming Guide which will let you know in depth what to do.
Below is the snapshot for which you are looking into:
Hope this will help you. Happy coding :)

Encode JSON data for URL

In iOS, I want to send JSON data in URL to make service call. I tried following code snipped but Encoded URL seems wrong. Because in JSON there is a colon character (:) between key and value and comma character (,) for separation. But, i am not able to encode colon(:) as %3A and comma(,) as %2C
Code Snippet:
- (NSURL *)getEncodedUrl {
// Build dictionnary with parameters
NSString *abc = #"abc";
NSNumber *limitNumber = [NSNumber numberWithInt:2];
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:limitNumber forKey:#"limit"];
[dictionnary setObject:abc forKey:#"abc"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary options:0 error:&error];
if (!jsonData) {
debug("Json error %#",error);
return nil;
} else {
NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
debug("Json op %#",JSONString);
NSString* params = [JSONString stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://baseUrl.com?param=#",params]];
debug("URL = %#",url);
return url;
}
}
OUTPUT:~
URL = http://baseUrl.com?param=%7B%22abc%22:%22abc%22,%22limit%22:2%7D
(Include colon and comma characters)
But I want following o/p:
http://baseUrl.com?param=%7B%22abc%22%3A%22abc%22%2C%22limit%22%3A2%7D
(No colon and comma characters)
Online Encoding-Decoding Site that I am referring as of now.
http://www.url-encode-decode.com/
you can simply use
NSString *url = #"http://baseUrl.com?param=%7B%22abc%22:%22abc%22,%22limit%22:2%7D";
NSString *encodeImgUrl = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
I'd recommend that you send the JSON as POST data instead of the GET that you're using. It'd be more straightforward to package it as MIME data and any encoding you do would be easier to understand.
So you are trying to generate the query portion of a URL here. Colons are a perfectly legitimate character to include in URL queries. I wrote an article covering the intricacies of escaping URL queries in Cocoa:
http://www.mikeabdullah.net/escaping-url-queries-in-cocoa.html
Since you're keen to perform extra escaping, I suggest taking my sample code and extending it to specially ask for : and ; characters to be escaped too.
I made small mistake in API call that is why I am getting wrong result. There is no need to encode colon(:) as %3A and comma(,) as %2C.
One more thing I would like to share with you. You can use base64 string instead of encoding JSON part.

iOS Read a Stream but returns null

Ok boys and girls, this is my prob :
I'd like to read a JSON stream in my iOS app, but when i tried, it returns
2013-04-12 02:35:01.479 Test[81414:303] (null)
but my file exist and is absolutely not empty !! You can find it here http://api.kalokod.com/cce/mainfeed.json
And my script to read it is :
NSError *error;
NSURL *file = [NSURL URLWithString:#"http://api.kalokod.com/cce/mainfeed.json"];
NSString *string = [NSString stringWithContentsOfURL:file
encoding:NSUTF8StringEncoding
error:&error];
NSLog(#"%#", string);
I tested your code, and received a Cocoa Error 261. This means that the JSON you are trying to load isnt encoded with UTF-8, so using NSUTF8StringEncoding wont work. Try this
NSString *string = [NSString stringWithContentsOfURL:file
encoding:NSASCIIStringEncoding
error:&error];
I suspect this might be your problem -- that there are non-UTF8 characters in your JSON string.
Log your NSError *error to see if you get a Cocoa error 261.

Encrypted twitter feed

I'm developing an iOS application , that will take a twits from twitter,
I'm using the following API
https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&count=2&screen_name=TareqAlSuwaidan
The problem are feed in Arabic Language ,
i.e the text feed appears like this
\u0623\u0646\u0643 \u0648\u0627\u0647\u0645
How can i get the real text (or how to encode this to get real text) ?
This is not encrypted, it is unicode. The codes 0600 - 06ff is Arabic. NSString handles unicode.
Here is an example:
NSString *string = #"\u0623\u0646\u0643 \u0648\u0627\u0647\u0645";
NSLog(#"string: '%#'", string);
NSLog output:
string: 'أنك واهم'
The only question is exactly what problem are you seeing, are you getting the Arabic text? Are you using NSJSONSerialization to deserialize the JSON? If so there should be no problem.
Here is an example with the question URL (don't use synchronous requests in production code):
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&count=2&screen_name=TareqAlSuwaidan"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSDictionary *object1 = [jsonObject objectAtIndex:0];
NSString *text = [object1 objectForKey:#"text"];
NSLog(#"text: '%#'", text);
NSLog output:
text: '#Naser_Albdya أيدت الثورة السورية منذ بدايتها وارجع لليوتوب واكتب( سوريا السويدان )
Those are Unicode literals. I think all that's needed is to use NSString's stringWithUTF8String: method on the string you have. That should use NSString's native Unicode handling to convert the literals to the actual characters. Example:
NSString *directFromTwitter = [twitterInterface getTweet];
// directFromTwitter contains "\u0623\u0646\u0643 \u0648\u0627\u0647\u0645"
NSString *encodedString = [NSString stringWithUTF8String:[directFromTwitter UTF8String]];
// encodedString contains "أنك واهم", or something like it
The method call inside the conversion call ([directFromTwitter UTF8String]) is to get access to the raw bytes of the string, that are used by stringWithUTF8String. I'm not exactly sure on what those code points come out to, I just relied on Python to do the conversion.

Resources