NSDictionary shows nil in IOS/ Objective c - ios

I am receiving an arabic data through web service. I get data as a JSON object, but when I pass the value to an NSDictionary it shows nil and am not able to get key/pair value.i receive value till data,but i cant pass that to NSDictionary.
Here is the code:
(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
for (NSString *key in [json allKeys])
{
NSArray *feed = [json objectForKey:key];
for(int i=0; i<feed.count;i++)
{
for (NSString *key1 in [[feed objectAtIndex:i] allKeys])
{
if([key1 isEqualToString:#"newsTitle"])
{
NSString *value = [[feed objectAtIndex:i] objectForKey:key1];
[NewsTitleArray addObject:value];
}
else if([key1 isEqualToString:#"newsDescription"])
{
NSString *value = [[feed objectAtIndex:i] objectForKey:key1];
[NewsDescriptionArray addObject:value];
}}}}

You need to use proper encoding for your data, normally arabic content require ISO-Latin encoding. Though your code is wrong, you need to use correct NSURLConnection Delegate function to get complete data, you are trying to parse the incomplete data
See the changes below
Declare a variable
NSMutableData *receivedData;
Handle the delegate calls
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
//This delegate function gets called multiple times while fetching the data..
if(!receivedData){
receivedData=[[NSMutableData alloc] initWithData:data];
}else{
[receivedData appendData:data];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
//When the connection completes the processing, do you parsing
if(receivedData.length>0){
NSString *string = [[NSString alloc] initWithData:receivedData encoding:NSISOLatin1StringEncoding];
NSData *utf8Data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:utf8Data options:kNilOptions error:nil];
for (NSString *key in [json allKeys])
{
NSArray *feed = [json objectForKey:key];
for(int i=0; i<feed.count;i++)
{
for (NSString *key1 in [[feed objectAtIndex:i] allKeys])
{
if([key1 isEqualToString:#"newsTitle"])
{
NSString *value = [[feed objectAtIndex:i] objectForKey:key1];
[NewsTitleArray addObject:value];
}
else if([key1 isEqualToString:#"newsDescription"])
{
NSString *value = [[feed objectAtIndex:i] objectForKey:key1];
[NewsDescriptionArray addObject:value];
}
}
}
}
}
Note: The code above is not tested, might not work at first go, but it should be this way.
I hope it helps.
Cheers.

Related

Xcode - Special characters in JSON

Im loading a database from a website through JSON. When I download the database I use UTF8 to make all characters appear correctly and when I NSLOG them it all appears as it should. But when I analyze the data using JSON and afterwards try to filter out just a few of the words, the words with special characters become like this: "H\U00f6ghastighetst\U00e5g" where it should say: "Höghastighetståg".
I have tried to find a way to make the code convert the text back to UTF8 after filtering but somehow I can't make it happen. Would be really helpful for some answers.
NSError *error;
NSString *url1 = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.pumba.se/example.json"] encoding:NSUTF8StringEncoding error:&error];
NSLog(#"Before converting to NSData: %#", url1);
NSData *allCoursesData = [url1 dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *JSONdictionary = [NSJSONSerialization
JSONObjectWithData:allCoursesData
options:kNilOptions
error:&error];
if( error )
{
NSLog(#"%#", [error localizedDescription]);
}
else {
NSMutableArray *allNames = [NSMutableArray array];
NSArray* entries = [JSONdictionary valueForKeyPath:#"hits.hits"];
for (NSDictionary *hit in entries) {
NSArray *versions = hit[#"versions"];
for (NSDictionary *version in versions) {
NSDictionary *properties = version[#"properties"];
NSString *status = [properties[#"Status"] firstObject];
NSString *name = [properties[#"Name"] firstObject];
if ([status isEqualToString:#"usable"]) {
[allNames addObject:name];
}
}
}
NSLog(#"All names: %#", allNames);
}}
try with
+ (NSString *)utf8StringEncoding:(NSString *)message
{
NSString *uniText = [NSString stringWithUTF8String:[message UTF8String]];
NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding];
message = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding];
return message;
}
or
+ (NSString *)asciiStringEncoding:(NSString *)message
{
const char *jsonString = [message UTF8String];
NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
message = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];
return message;
}
and this code can help you
+ (NSDictionary *)jsonStringToObject:(NSString *)jsonString
{
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse;
if (data)
jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
return jsonResponse;
}
+ (NSString *)objectToJsonString:(NSDictionary *)dict
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (jsonData.length > 0 && !error)
{
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return jsonString;
}
return nil;
}

How to parse nsdictionary data using nsserlization.?

I have dictionary data like this and one array on image.
{ "result":"Successful","data":{"id":"12","product_name":"12\" Round
Plate","sku":"ECOW12RP","description":"Diameter 12 inch x\tDepth 0.9
inch","price":"153.00","business_price":"365.00","image":[{"image":"1454499068ecow12rp_01.jpg"}],"pack_size":"20","business_pack_size":"50","category":"2,3","tax_class":"1","created":"2016-02-03","altered":"2016-02-03
17:52:58","status":"1","deleted":"0","arrange":"1","delivery":"150.00"}}
I want to parse all the key values from it. this is the code which i use for this task.
-(void)viewDidLoad
{
NSLog(#"d %ld", (long)id);
NSString* myNewString = [NSString stringWithFormat:#"%i", id];
NSURL *producturl = [NSURL URLWithString:#"http://dev1.brainpulse.org/ecoware1/webservices/product/" ];
NSURL *url = [NSURL URLWithString:myNewString relativeToURL:producturl];
NSData * imageData = [NSData dataWithContentsOfURL:url];
UIImage * productimage = [UIImage imageWithData:imageData];
NSURL *absURL = [url absoluteURL];
NSLog(#"absURL = %#", absURL);
NSURLRequest *request= [NSURLRequest requestWithURL:absURL];
[NSURLConnection connectionWithRequest:request delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response
{
data = [[NSMutableData alloc] init];
NSLog(#"Did receive response");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)thedata
{
[data appendData:thedata];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSDictionary *dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:#"data"];
NSLog(#"arr %#", dictionary);
[productdetail removeAllObjects];
for (NSString *tmp in dictionary)
NSMutableDictionary *temp = [NSMutableDictionary new];
[temp setObject:#"product_name" forKey:#"product_name"];
//[temp setObject:[tmp objectForKey:#"id"] forKey:#"id"];
// [temp setObject:[tmp objectForKey:#"image"] forKey:#"image"];
[productdetail addObject:temp];
NSLog(#"detail %#", productdetail);
}
I tried to parse string from nsdictionary with the help of for loop, but I get product details array null, i don't know why it not get key value.
i am parse data which is in nsdictionary but i have null array when i try to parse image array in this json data please look at this json data.
{"result":"Successful","data":{"id":"2","product_name":"6\" Round Plate","sku":"ECOW6RP","description":"Diameter 6.0 (inch) x Depth 0.6 (inch)\r\n\r\nPerfect for finger foods!","price":"42.89","business_price":"100.00","image":[{"image":"1454499251ecow6rp_01.jpg"}],"pack_size":"20","business_pack_size":"50","category":"2,3","tax_class":"1","created":"2016-01-19","altered":"2016-02-06 16:06:10","status":"1","deleted":"0","arrange":"1","delivery":"150.00"}}
try this
Option-1
NSDictionary *dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:#"data"];
[productdetail removeAllObjects];
if (dictionary)
{
NSMutableDictionary *temp = [NSMutableDictionary new];
[temp setObject:[dictionary objectForKey:#"product_name"] forKey:#"product_name"];
[productdetail addObject:temp];
}
Regarding your specific question to get the product_name data into your dictionary, this will work
NSDictionary *dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:#"data"];
NSMutableDictionary *temp = [NSMutableDictionary new];
if ([dictionary objectForKey:#"product_name"]){
[temp setObject:[dictionary objectForKey:#"product_name"] forKey:#"product_name"];
}
If you print out the dictionary you made, you should see it is in there.
NSLog(#"the temp dictionary value for ProductName: %#", [temp objectForKey:#"product_name"];

JSON Data Not Parsed in iOS

i am Newbie in iOS Development. I want to Parse an JSON Data From My WebServices for that I have written folliwing code
- (void)viewDidLoad
{
NSURL * url=[NSURL URLWithString:[NSString stringWithFormat:#"http://www.janvajevu.com/webservice/latest_post.php?page=%d",pageNum]];
dispatch_async(kBgQueue, ^{
data = [NSData dataWithContentsOfURL: url];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
-(void)fetchedData:(NSData *)responsedata
{
if (responsedata.length > 0)
{
NSError* error;
self.json= [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
if ([[_json objectForKey:#"data"] isKindOfClass:[NSArray class]])
{
NSArray *arr = (NSArray *)[_json objectForKey:#"data"];
[self.navuArray addObjectsFromArray:arr];
[self.navuTable reloadData];
NSLog(#"JSON Data %#",self.navuArray);
}
self.navuTable.hidden=FALSE;
}
Here Self.json is A JSON Dictionary and self.navuArray is my NSMutableArray when i print my Array then It returns Num. Please Give me Solution for it.
Its your navuArray that is not initialized before you are adding objects to it from array. Initialize it before you call for your data and then add objects to it.
Try this code
id jsonObject = [NSJSONSerialization JSONObjectWithData:webData options:kNilOptions error:&error];
table = [[UITableView alloc]init];
[dict objectForKey:#"data"];
NSArray *array = (NSArray *)jsonObject;
if ([[dict objectForKey:#"data"] isKindOfClass:[NSArray class]])
{
for(int i=0;i<[array count];i++)
{
dict1 = [array objectAtIndex:i];
[postIdArr addObject:[dict objectForKey:#"post_id]];
[postTitleArr addObject:[dict objectForKey:#"post_title"]];
[postTitleSlungArr addObject:[dict objectForKey:#"post_title_slug"]];
NSString *dateId = [dict objectForKey:#"post_date"];
NSArray *dateArray = [dateId componentsSeparatedByString:#" "];
[dateArrs addObject:[dateArray objectAtIndex:0]];
[timeArrs addObject:[dateArray objectAtIndex:1]];
//[dateIdArr addObject:[dict objectForKey:#"date"]];
[postViewsArr addObject:[dict objectForKey:#"post_views"]];
[imageArr addObject:[dict objectForKey:#"feature_image"]];
[shortArr addObject:[dict objectForKey:#"short_description"]];
[nameArr addObject:[dict objectForKey:#"author_name"]];
}

location of places on the google-map fetched by an array

Hello friends
Google-map-SDK
I am new to ios and working on the GOOGLE-MAP-SDK. and everything is going very well,but i am not able to use the annotations in this case due to which i am not able to locate my positions which i fetched from the placeAPI of the google.
So kindly help me out with my errors.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Code File
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-(IBAction)search:(id)sender
{
NSString *url = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=30.7343000,76.7933000&radius=500&types=food&name&sensor=true&key=AIzaSyCGeIN7gCxU8baq3e5eL0DU3_JHeWyKzic"];
//Formulate the string as URL object.
NSURL *googleRequestURL=[NSURL URLWithString:url];
// Retrieve the results of the URL.
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
//The results from Google will be an array obtained from the NSDictionary object with the key "results".
NSArray* places = [json objectForKey:#"results"];
//Write out the data to the console.
NSLog(#"Google Data: %#", places);
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here is the code from which i will recive the data and want to display it on the googlemap.
NSLog(#"Google Data: %#", places); is giving me the out put...
...
NSArray *markerForplaces = [NSMutableArray arrayWithCapacity:[responseResults count]];
for (NSDictionary *dict in responseResults) {
GMSMarker *markerForplace = [self markerForGooglePlaceFromDictionary:dict error:nil];
if (markerForplace) {
[markerForplaces addObject:markerForplace];
markerForplace.map = self.mapView;
}
}
...
- (GMSMarker*)markerForGooglePlaceFromDictionary:(NSDictionary*)dict {
CLLocationCoordinate2D coordinate = [self coordinateForPlace:dict];
GMSMarker *marker = [GMSMarker markerWithPosition:coordinate];
marker.userInfo = dict; //save place
}
- (CLLocationCoordinate2D)coordinateForPlace:(NSDictionary*)dictionary {
NSDictionary *geo = [dictionary objectForKey:#"geometry"];
if ([geo isKindOfClass:[NSDictionary class]]) {
NSDictionary *loc = [geo objectForKey:#"location"];
if ([loc isKindOfClass:[NSDictionary class]]) {
NSString *lat = [loc objectForKey:#"lat"];
NSString *lng = [loc objectForKey:#"lng"];
return CLLocationCoordinate2DMake([lat doubleValue], [lng doubleValue]);
}
}
return CLLocationCoordinate2DMake(0, 0);
}

Unrecognized selector sent to instance in JSON parsing

Please help me debug this code
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:#"http://cnapi.iconnectgroup.com/api/UserProfile?id=1"]];
NSString *json = [NSString stringWithContentsOfURL:urls encoding:NSASCIIStringEncoding error:&error];
NSLog(#"JSon data = %# and Error = %#", json, error);
if(!error)
{
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSLog(#"JSON data is :: %#", myJsonArray);
for(NSDictionary *jsonDictionary in myJsonArray)
{
//NSString *uids = jsonDictionary[#"UID"];
NSString *address1 = jsonDictionary[#"Address1"];
NSString *address2 = jsonDictionary[#"Address2"];
NSString *city = jsonDictionary[#"City"];
NSString *emailId = jsonDictionary[#"EmailID"];
NSString *fname = jsonDictionary[#"FName"];
NSString *fax = jsonDictionary[#"Fax"];
NSString *lname = jsonDictionary[#"LName"];
NSString *password = jsonDictionary[#"Password"];
NSString *phone = jsonDictionary[#"Phone"];
NSString *state = jsonDictionary[#"State"];
NSString *uids = [jsonDictionary objectForKey:#"UID"];
NSString *zip = jsonDictionary[#"Zip"];
NSString *company = jsonDictionary[#"company"];
NSString *department = jsonDictionary[#"department"];
NSLog(#"Uid is = %#", uids);
NSLog(#"First Name = %#", fname );
NSLog(#"Last Name = %#", lname);
NSLog(#"Company = %#", company);
NSLog(#"Email Id = %#", emailId);
NSLog(#"Password = %#", password);
NSLog(#"Department = %#", department);
NSLog(#"Address 1 = %#", address1);
NSLog(#"Address 2 = %#", address2);
NSLog(#"City = %#", city);
NSLog(#"State = %#", state);
NSLog(#"Zip = %#", zip);
NSLog(#"Phone = %#", phone);
NSLog(#"Fax = %#", fax);
}
}
});
[activity stopAnimating];
self.activity.hidden = YES;
}
Image will give you where the error is. I get this error after clicking stepover to debug. I also tried
NSString *address1 = [jsonDictionary objectForKey:#"Address1"];
From the output of url, it shows it's not array but a dictionary. You are trying to convert to array here.
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
instead use this
NSDictionary *myJsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
then remove that for loop no need of it. and replace your variable jsonDictionary with myJsonDictionary so to retrieve values.
// for(NSDictionary *jsonDictionary in myJsonArray)
Run now it will be fine. Worked for me fine
If the output was array of Dictionaries it would have been looked like this with square brackets around.
For Ex: [{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]
If you are not sure of nature of response from url you can check for
the type. For ex:
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(#"its an array!");
NSArray *myJsonArray = (NSArray *)jsonObject;
// Handle Array of Dictionary
for(NSDictionary *jsonDictionary in myJsonArray)
{
NSString *address1 = jsonDictionary[#"Address1"];
//and so on
}
}
else {
NSLog(#"It's Dictionary");
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSLog(#"jsonDictionary - %#",jsonDictionary);
//Handle NSDictionary
}
jsonDictonary is a NSString not as you expect NSDictonary.
Double check your JSON and maybe before calling that function check if it's NSDictonary.
Your should use one of the semi-standard frameworks for parsing JSON into Core Data. There are some SO questions about those.
In this case, your JSON has only one object which is not an array.
In general, your app shouldn't abort if server sent something unexpected, so it's better to use a parser which will loudly complain about malformed JSON than with it from scratch.

Resources