I'm trying to fetch data in iOS 9 like this:
NSError *error = nil;
NSData *avaliableVersion = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://energyapp.co/fonts/vers.php"] options:0 error:&error];
NSString *str = [[NSString alloc]initWithData:avaliableVersion encoding:NSUTF8StringEncoding];
NSLog(str);
As a result, it loads very long time, but here is just few symbols. And result in "str" is empty.
Related
I am using a NSURLConnect call and I get unsupported URL when I have a space in my query string. To fix this I converted the string to base64 and I am still getting errors. How do I send a base64 string though NSUrlConnect successfully? If this isn't possible, how do I safely send a string with a space in it?
NSData *convertData = [queryWS dataUsingEncoding: NSUnicodeStringEncoding];
queryWS = [convertData base64EncodedStringWithOptions:kNilOptions];
NSURLRequest *urlRequest =
[NSURLRequest requestWithURL:[NSURL URLWithString:queryWS]];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if (!error) {
responseDictionary =
[NSJSONSerialization JSONObjectWithData:data
options:0
error:&parseError];
You do not want to convert the URL string to base64 encoding. What you want is to properly escape any special characters in the URL. Please see the NSString stringByAddingPercentEscapesUsingEncoding: method or NSString stringByAddingPercentEncodingWithAllowedCharacters: if you only need to support iOS 9 or later.
NSString *queryString = #"SOME_QUERY_STRING";
NSString *encodedQueryString = [queryString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
I have the following code :
NSData * jsonData = [NSData dataWithContentsOfURL:location];
NSString* newStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *data = [newStr dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
if (jsonError) {
NSLog(#"JSON Error %#", [jsonError localizedDescription]);
}
NSArray * jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
Which is parsing the following JSON String :
{"author":"Oli Riman","content":"The museum shows us a view of pre-WWI society that includes doubts, fears, political protests etc. through newspaper cartoons of the time. Really interesting for adults who enjoy history. I wouldn't suggest this for kids who haven't studied WWI history or who don't read easily.","rating":"5","placeId":"40","date":"29-June-2015","reviewId":"9905A52D-76B2-4D42-8CA8-9158225C0D07"}
However I am getting a strange error code of :
domain: (null) - code: 0
Can anyone advise on what is causing this ?
Just tested the code on my simulator. Its working. You need to check if you are getting data from server or not.
If you want to test the parsing thing, you can do one thing-
Just store the data in json file and save it in the app bundle lets say file is "data.json"
and call below method, you will get data for sure.
- (void)readJsonData {
NSString *path = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"json"];
NSURL *url = [NSURL fileURLWithPath:path];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData: data
options: NSJSONReadingAllowFragments
error: &error];
NSLog(#"Parsed json data- %#", dict);
}
This question already has an answer here:
Parsing JSON response .
(1 answer)
Closed 8 years ago.
Hai I need to get the id & status from the service for login my code is below. please guide me to get the values.. Thanks in advance..
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.xxx/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSData *data=[NSData dataWithContentsOfURL:url];
1st Do the jSon parsing and then get the particular value from the
key .
Before getting any value , we have to understand the tree of jSon.
Here "posts" is an NSArray ,within that one DIctionary "post" is
there ,which again contains another dictionary.
Below is the complete code.
(void)viewDidLoad
{
[super viewDidLoad];
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link =
[NSString stringWithFormat:#"http://www.some.com/webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
}); }
Then call that selector fetchedData
(void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
if(!error){
NSArray* postArray = [json objectForKey:#“posts”]; //This is an array
if (postArray.count>0) {
NSDictionary *dict = [[postArray objectAtIndex:0] objectForKey:#"post" ];
NSString *id_ = [dict objectForKey:#"id"];
NSString *status_ = [dict objectForKey:#"status"];
}
}
}
Can you post your json string. You can use NSJSONSERIALISATION to convert data (json string ) into NSDictionary. Then use the keys to extract the values. I'm replying through mobile so I can't write the actual code.
Use Below code to parse Json in IOS
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.some.com/_webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSMutableURLRequest *req1 = [NSMutableURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
//getting the data
NSData *newData = [NSURLConnection sendSynchronousRequest:req1 returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
NSLog(#"basavaraj \n\n\n %# \n\n\n",responseString);
NSData* data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
NSString *id=[res objectForKey:#"ID"];
NSString *status=[res objectForKey:#"Status"];
and if u need extra info please go through below link it may help you
Click here for more details
As the question says, I get an unexpected output when importing JSON into a TableView class.
JSON:
{"city":"Cambridge"}{"city":"Oxford"}
Objective-C:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.domain.com/cities.php"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"%#", response);
Output:
<7b226369 7479223a 2243616d 62726964 6765227d 7b226369 7479223a 224f7866 6f726422 7d>
Fairly sure I'm structuring my JSON wrongly...
Your response is of NSData type and needs to be converted to a string.
NSString *responseString = [[NSString alloc] initWithBytes:[response bytes] length:[response length] encoding:NSUTF8StringEncoding];
NSLog(responseString);
You can also use the initWithData as described elsewhere
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
While this is useful for debugging, to actually extract or work with the data, you will want to convert it to dictionary or array.
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:response options:0 error:NULL];
From here, you can reference items in the dictionary.
NSArray *responseArray = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:nil];
NSLog(#"%#",responseArray);
NSMutableArray *cityArray =[[NSMutableArray alloc] init];
for (int i=0; i<[responseArray count]; i++)
{
[cityArray addObject:[NSString stringWithFormat:#"%#",[[responseArray objectAtIndex:i] valueForKey:#"city"];
}
Please note that, I believe you would fix that json and make it to json returning an array.
NSString *jsonStr = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%#",jsonStr);
I need to get contents of an XML file which is hosted on web, and parse it.
I decided to use TouchXML for parsing process. However, I cannot get contents of the file since it is encoded with ISO-8859-9
XML File Url: http://rss.haberler.com/mobil/sondakika2.asp?kategori=manset
I have tried 2 different approachs.
1) Getting contents of url into NSString:
NSString *url = #"http://rss.haberler.com/mobil/sondakika2.asp?kategori=manset";
NSError *error = nil;
NSStringEncoding encoding;
NSString *xmlString = [[NSString alloc] initWithContentsOfURL: [NSURL URLWithString:url] usedEncoding:&encoding error:&error];
xmlString becomes null, and error description says:
The operation couldn’t be completed. (Cocoa error 261.)
Instead of usedEncoding, I also tried specifying encoding explicitly, from UTF-8 to NSISOLatin1StringEncoding and NSISOLatin2StringEncoding (unfortunately, I could not find NSISOLatin9StringEncoding).
2) I also tried to load xml into NSData.
NSError *error = nil;
NSData *XMLData = nil;
XMLData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:url] options:0 error:&error];
When I constructed XML Parser, specific characters are unknown and application terminates when I get string values.
CXMLDocument *doc = [[CXMLDocument alloc] initWithData:XMLData options:0 error:nil];
NSArray *nodes = [doc nodesForXPath:#"//item" error:nil];
for (CXMLElement *node in nodes) {
for(int counter = 0; counter < [xmlElement childCount]; counter++) {
CXMLNode * child = [xmlElement childAtIndex:counter];
NSString *childName = child.name;
NSString * childValue = [child stringValue];
}
}
Getting stringValue of child terminates application with SIGABRT.
How can I fix the problem?
From the TouchXML CXMLDocument.m file, this is what initWithData: looks like
- (id)initWithData:(NSData *)inData options:(NSUInteger)inOptions error:(NSError **)outError
{
return [self initWithData:inData encoding:NSUTF8StringEncoding options:inOptions error:outError];
}
What you could try doing is, in this file, replace NSUTF8StringEncoding with NSASCIIStringEncoding or whatever encoding it uses. That may fix it.