How to use google Api for find places around me - ios

I am working on app which use Google API. I am trying to find places around me by it. I am using below code for fetch data,
-(void)fetchedData:(NSData *)responseData {
//this is to parse out the json data
NSError *error = nil; //create some error handling here
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
//I'm told the returned results from Google will be an array obtained from the NSDictionary object with the key "results"
NSArray *places = [json objectForKey:#"results"];
//display the data to the console for review
NSLog(#" Google data:\n%#", places);
}
But it shows json status = Request Denied.
Any help will appreciated.

Vishal,
You can do it using the following block of Code:
- (void) queryGooglePlaces: (NSString *) googleType
{
NSString *url = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%#&types=%#&sensor=true&key=%#&language=%#", appDelegate.currentLatitude, appDelegate.currentLongitude, [radiusValueArray objectAtIndex:[[NSUserDefaults standardUserDefaults] integerForKey:#"selectedDistance"]], googleType, kGOOGLE_API_KEY, appDelegate.selectedLanguageCode];
//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];
if(data == nil)
{
[placeTableView reloadData];
[SVProgressHUD dismiss];
}
else
{
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
}
});
}
- (void) queryGooglePlaces_WithNextPage
{
// Build the url string we are going to sent to Google. NOTE: The kGOOGLE_API_KEY is a constant which should contain your own API key that you can obtain from Google. See this link for more info:
NSString *url = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?pagetoken=%#&location=%f,%f&radius=%#&sensor=true&key=%#", nextPageToken, appDelegate.currentLatitude, appDelegate.currentLongitude, [radiusValueArray objectAtIndex:[[NSUserDefaults standardUserDefaults] integerForKey:#"selectedDistance"]], kGOOGLE_API_KEY];
//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];
if(data == nil)
{
[placeTableView reloadData];
[SVProgressHUD dismiss];
}
else
{
[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".
if(isNextPageAvailable == FALSE)
[appDelegate.placesArray removeAllObjects];
NSArray *placesTemp = [json objectForKey:#"results"];
if([json valueForKey:#"next_page_token"] != nil)
{
nextPageToken = [json valueForKey:#"next_page_token"];
isNextPageAvailable = TRUE;
}
else
{
nextPageToken = #"";
isNextPageAvailable = FALSE;
}
for(int i=0;i<[placesTemp count];i++)
{
NSMutableDictionary *placeDictionary = [[NSMutableDictionary alloc] initWithDictionary:[placesTemp objectAtIndex:i]];
double lat1 = appDelegate.currentLatitude;
double long1 = appDelegate.currentLongitude;
double lat2 = [[[[placeDictionary objectForKey:#"geometry"] objectForKey:#"location"] valueForKey:#"lat"] doubleValue];
double long2 = [[[[placeDictionary objectForKey:#"geometry"] objectForKey:#"location"] valueForKey:#"lng"] doubleValue];
CLLocation *location1 = [[CLLocation alloc] initWithLatitude:lat1 longitude:long1];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:lat2 longitude:long2];
[placeDictionary setValue:[NSString stringWithFormat:#"%f",[location1 distanceFromLocation:location2]] forKey:#"distance"];
[appDelegate.placesArray addObject:placeDictionary];
}
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"distance" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 floatValue] < [obj2 floatValue])
return NSOrderedAscending;
else
return NSOrderedDescending;
}];
NSArray *sortedArray = [appDelegate.placesArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[appDelegate.placesArray removeAllObjects];
[appDelegate.placesArray addObjectsFromArray:sortedArray];
[self showPoweredbyGoogle];
[placeTableView reloadData];
[SVProgressHUD dismiss];
// [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:#selector(reloadTableNow) userInfo:nil repeats:NO];
//Plot the data in the places array onto the map with the plotPostions method.
// [self plotPositions:placesArray];
}
- (void) queryGooglePlaceDetail
{
NSString *url = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/details/json?reference=%#&sensor=false&key=%#&language=%#", [[appDelegate.placesArray objectAtIndex:selectedPlaceIndex] valueForKey:#"reference"], kGOOGLE_API_KEY, appDelegate.selectedLanguageCode];
//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];
if(data == nil)
{
[SVProgressHUD dismiss];
}
else
{
[self performSelectorOnMainThread:#selector(fetchedDetailPlaceData:) withObject:data waitUntilDone:YES];
}
});
}
- (void)fetchedDetailPlaceData:(NSData *)responseData
{
//parse out the json data
NSError* error;
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSDictionary *detailTempDic = [[NSMutableDictionary alloc] initWithDictionary:[json objectForKey:#"result"]];
[detailTempDic setValue:[[appDelegate.placesArray objectAtIndex:selectedPlaceIndex] valueForKey:#"distance"] forKey:#"distance"];
[SVProgressHUD dismiss];
[self performSegueWithIdentifier:#"Detail_Place_Push" sender:detailTempDic];
}
Here you have to pass different types of objects from Google Places such as atm, airport, restaurant, bank, hospital, school.
[self queryGooglePlaces:[googlePlaceTypeArray objectAtIndex:SharedManager.selectedPlaceCategoryIndex]];
Thanks,
Best Regards,
Gurprit

Related

Objective C JSON parse from NSMutableArray

I have a JSON like below (getting from an URL)-
{
action :getAllJournal;
data :{
journalList :[{
cancelled : F;
"cust_code" : "700-T022";
"journal_amount" : 2216;
"journal_code" : "JV1603/001";
"journal_date" : "2016-03-15 00:00:00";
"journal_id" : 1;
outstanding : 0;
},
{
cancelled : F;
"cust_code" : "700-0380";
"journal_amount" : 120;
"journal_code" : "JV1605/006";
"journal_date" : "2016-05-31 00:00:00";
"journal_id" : 2;
outstanding : 120;
},
{
cancelled : F;
"cust_code" : "700-T280";
"journal_amount" : 57;
"journal_code" : "JV1609/001";
"journal_date" : "2016-09-22 00:00:00";
"journal_id" : 3;
outstanding : 0;
}
];
};
message = "";
"message_code" = "";
result = 1;}
The code below doing is getting the JSON from URL and storing them in NSMutableArray. Until storing them into array, it's working fine but I'm bit confused with the JSON format and don't know how to get result by a key.
__block NSMutableArray *jsonArray = nil;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlString = [NSString stringWithFormat:#"http://xxxxxxx/api.php?action=getAllJournal"];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
{
if (data)
{
id myJSON;
#try {
myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
#catch (NSException *exception) {
}
#finally {
}
jsonArray = (NSMutableArray *)myJSON;
NSString *nsstring = [jsonArray description];
NSLog(#"IN STRING -> %#",nsstring);
NSData *data = [nsstring dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if(jsonObject !=nil){
if(![[jsonObject objectForKey:#"journalList"] isEqual:#""]){
NSMutableArray *array=[jsonObject objectForKey:#"journalList"];
NSLog(#"array: %lu",(unsigned long)array.count);
int k = 0;
for(int z = 0; z<array.count;z++){
NSString *strfd = [NSString stringWithFormat:#"%d",k];
NSDictionary *dicr = jsonObject[#"journalList"][strfd];
k=k+1;
// NSLog(#"dicr: %#",dicr);
NSLog(#"cust_code - journal_amount : %# - %#",
[NSMutableString stringWithFormat:#"%#",[dicr objectForKey:#"cust_code"]],
[NSMutableString stringWithFormat:#"%#",[dicr objectForKey:#"journal_amount"]]);
}
}
}else{
NSLog(#"Error - %#",jsonError);
}
}
}];
From this, I am able to get the JSON successfully. But it's always giving me this error: Error Domain=NSCocoaErrorDomain Code=3840 "No string key for value in an object around character 6." UserInfo={NSDebugDescription=No string key for value in an object around character 6.} How can I get all values from journalList? I'm new to iOS, that's why not sure what I'm missing.
id myJSON;
#try {
myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
#catch (NSException *exception) {
}
#finally {
}
jsonArray = (NSMutableArray *)myJSON;
NSString *nsstring = [jsonArray description];
NSLog(#"IN STRING -> %#",nsstring);
NSData *data = [nsstring dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
I'd say: NO and NO.
I wouldn't do a #try/#catch on a NSJSONSerialization, because the real issues are on the error parameter (and they won't throw a NSException for most of the cases). Just check if (data) is quite efficient.
Then, let's say it worked, and you have myJSON.
In fact, myJSON is a NSDictionary, not a NSArray, so the cast is useless and doesn't make sense.
Next issue:
Your are using -description (okay, if you want to debug), but you CAN'T use it to reconstruct AGAIN a JSON. It's not a valid JSON, it's the way the compiler "print" an object, it adds ";", etc.
If your print [nsstring dataUsingEncoding:NSUTF8StringEncoding] and data you'll see that they aren't the same.
For a more readable:
NSString *dataJSONStr = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];, it's clearly not the same structure as your nsstring.
Then, you are redoing the JSON serialization? Why ?
So:
NSError *errorJSON = nil;
NSDictionary *myJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&errorJSON];
if (errorJSON)
{
NSLog(#"Oops error JSON: %#", errorJSON);
}
NSDictionary *data = myJSON[#"data"];
NSArray *journalList = data[#"journalList"]
for (NSDictionary *aJournalDict in journalList)
{
NSUInteger amount = [aJournalDict[#"journal_amount"] integerValue];
NSString *code = aJournalDict[#"journal_code"];
}
There is a dictionary named "data" you're not fetching, represented by {}.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if (!jsonError) {
// Fetch the journalList
NSArray *journalList = json[#"data"][#"journalList"];
// iterate over every entry and output the wanted values
for (NSDictionary *journal in journalList) {
NSLog(#"%# %#", journal[#"cust_code"], journal[#"journal_amount"]);
}
}
json[#"key"] is a short form of [json objectForKey:#"key"] I find easier to read.
That is not a valid JSON. Entries should be separated by comma ,, not semicolon ;
You need to fetch journalList from data.
Try below code:
This is demo code to create array like you:
NSMutableDictionary *jsonObject = [NSMutableDictionary new];
jsonObject[#"action"]= #"";
jsonObject[#"message"]= #"";
jsonObject[#"message_code"]= #"";
jsonObject[#"result"]= #"1";
NSMutableArray *ary1 = [NSMutableArray new];
for(int i=0;i<5;i++)
{
NSMutableDictionary *dd = [NSMutableDictionary new];
dd[#"cancelled"]= #"F";
dd[#"cust_code"]= #"F";
[ary1 addObject:dd];
}
NSMutableDictionary *dicjournal = [NSMutableDictionary new];
[dicjournal setObject:ary1 forKey:#"journalList"];
[jsonObject setObject:dicjournal forKey:#"data"];
This is main Logic:
NSMutableArray *journalList = [NSMutableArray new];
NSMutableDictionary *dic = [jsonObject valueForKey:#"data"];
journalList = [[dic objectForKey:#"journalList"] mutableCopy];
Looks like your JSON is invalid. You can see whether your JSON is correct or not using http://jsonviewer.stack.hu/ and moreover format it. Meanwhile your code is not using "data" key to fetch "journalList" array.
Code : -
NSDictionary *dic = [jsonObject valueForKey:#"data"];
NSMutableArray *arr = [dic objectForKey:#"journalList"];
for (int index=0 ; index < arr.count ; index++){
NSDictionary *obj = [arr objectAtIndex:index];
// Now use object for key from this obj to get particular key
}
Thanks #Larme and #Amset for the help. I was doing wrong the in the NSMutableArray part. The correct version of this code is in the below:
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlString = [NSString stringWithFormat:#"http://xxxxxxx/api.php?action=getAllJournal"];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
{
if (data)
{
id myJSON;
#try {
myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
#catch (NSException *exception) {
}
#finally {
}
NSArray *journalList = myJSON[#"data"][#"journalList"];
for (NSDictionary *journal in journalList) {
NSLog(#"%# %#", journal[#"journal_date"], journal[#"journal_amount"]);
}
}
}];

How to integrate NSUrlsession in ios

Hi I am very new to ios and in my app I am using NSUrlSession for integrating services.
Here my main problem is when I get a response from the server, I can't handle them properly.
When I get a correct response, then see the below json stucture:-
responseObject = {
{
Name = Broad;
DeptNo = A00;
BatchNo = 23;
DeptId = 120;
},
{
Name = James;
DeptNo = B00;
BatchNo = 23;
DeptId = 123;
},
}
when I get a wrong response, see the below json stucture:-
responseObject = {
error = 1;
message = "Invalid Code";
}
when I get a correct response from the server, I am getting an exception in my below if block(like __NSCFArray objectForKey:]: unrecognized selector sent to instance 0x1611c200') and when I get a wrong response then T get exception in my else block
Please help me how to handle them
my code:-
(void) GetCallService1: (id)MainResponse{
dispatch_async(dispatch_get_main_queue(), ^{
NameArray = [[NSMutableArray alloc]init];
IdArray = [[NSMutableArray alloc]init];
if([MainResponse objectForKey:#"error"] != nil)
{
NSLog(#"No data available");
}
else{
for (NSDictionary *obj in MainResponse) {
if([obj objectForKey:#"Name"] && [obj objectForKey:#"DeptNo"]) {
NSString * Name = [obj objectForKey:#"Name"];
[NameArray addObject:Name];
NSString * Id = [obj objectForKey:#"id"];
[IdArray addObject:Id];
}
}
}
});
}
1)Change Your implementation like below
2)I checked is it dictionary type & error key has some value
3)Earlier you were calling objectForKey on Array, therefore it was crashing
-(void) GetCallService1: (id)MainResponse{
dispatch_async(dispatch_get_main_queue(), ^{
NameArray = [[NSMutableArray alloc]init];
IdArray = [[NSMutableArray alloc]init];
//here I checked is it dictionary type & error key has some value
if ([MainResponse isKindOfClass:[NSDictionary class ]] &&[MainResponse objectForKey:#"error"])
{
NSLog(#"No data available");
}
else{
for (NSDictionary *obj in MainResponse) {
if([obj objectForKey:#"Name"] && [obj objectForKey:#"DeptNo"]) {
NSString * Name = [obj objectForKey:#"Name"];
[NameArray addObject:Name];
NSString * Id = [obj objectForKey:#"id"];
[IdArray addObject:Id];
}
}
}
});
}
Try this:
//Result Block
typedef void (^ResultBlock)(id, NSError*);
//URL request
-(void)requestURL:(NSURLRequest *)request withResult:(ResultBlock)resultHandler{
//URLSession
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {
if(!error){
NSError *jsonError = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if([result isKindOfClass:[NSArray class]]){
//Success
resultHandler(result,nil);
}
else if([result isKindOfClass:[NSDictionary class]]){
if([[result objectForKey:#"error"] integerValue]){
//Failure.
NSMutableDictionary *errorDetail = [NSMutableDictionary dictionary];
[errorDetail setValue:[result objectForKey:#"message"] forKey:NSLocalizedDescriptionKey];
NSError *error = [NSError errorWithDomain:#"Error" code:100 userInfo:errorDetail];
resultHandler(nil, errorDetail);
}
}
}
}];
[task resume];
}
//Call your requestURL method:
[self requestURL:request withResult:^(id result, NSError *error){
if(!error){
//Success, Read & update your list
}
else{
//Error
// NSLog(error.localizedDescription());
}
}];

afnetworking in singletone and waiting requests from another controller (objective c)

I am writing an Apple iPhone application.
A have got a class - singleton which sending a requests to the server (ServerManager) and a ViewController which using methods of singletone and another methods (analyzing requests for example).
How to perform queries from singletone in viewcontroller on the line? One after the other? Not parallel?
//for example authoriztion in Twitter
//here my query for the Twitter Server
- (void) getTweetsFromTW:(NSInteger) count
onSuccess:(void(^)(NSArray* news)) success
onFailure:(void(^)(NSError* error, NSInteger statusCode)) failure {
//NSString* countStr = [NSString stringWithFormat:#"%ld", count];
NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:#"ld", count], #"count", nil];
NSError* requestError = [[NSError alloc] init];
NSURLRequest* myRequest = [[[Twitter sharedInstance] APIClient]
URLRequestWithMethod:#"GET"
URL:#"https://api.twitter.com/1.1/statuses/home_timeline.json"
parameters:params
error:&requestError];
[[[Twitter sharedInstance] APIClient]
sendTwitterRequest:myRequest
completion:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (data) {
NSError* jsonError;
NSArray* jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
//NSLog(#"%#", jsonArray); //вывод ответа сервера
NSMutableArray* textsArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [jsonArray count]; i++) {
NSArray* test = [[NSArray alloc] initWithObjects:[jsonArray objectAtIndex:i], nil];
NSDictionary* dict = [NSDictionary dictionaryWithObjects:test
forKeys:[test valueForKey:#"intField"]];
NSDictionary* dictionary = dict[[[dict allKeys] objectAtIndex:0]];
//NSLog(#"%#", [dictionary objectForKey:#"text"]); //вывод текстов твитов
[textsArray addObject:[dictionary objectForKey:#"text"]];
}
if (success) {
success(textsArray);
}
}
}];
}
//here is my viewcontroller
[[ServerManager sharedManager] getTweetsFromTW:10
onSuccess:^(NSArray *news) {
for (int i = 0; i < [news count]; i++) {
NSLog(#"%#", [news objectAtIndex:i]);
}
[_textsFromTW addObjectsFromArray:news];
}
onFailure:^(NSError *error, NSInteger statusCode) {
}];
//I need send this requests in a line not parallel
[[ServerManager sharedManager] getNewsFromVK:300
filter:#"post"
onSuccess:^(NSArray *news) {
for (int i = 0; i < [news count]; i++) {
NSLog(#"%#", [[news objectAtIndex:i] objectForKey:#"text"]);
if ([[news objectAtIndex:i] objectForKey:#"text"] != nil) {
[_textsFromVK addObject:[[news objectAtIndex:i] objectForKey:#"text"]];
}
}
}
onFailure:^(NSError *error, NSInteger statusCode) {
}];

How to Parse Nested Dictionary JSON Data in iOS?

i am newbie in iOS Development. i want to parse my this JSON Data into to array First array Contain all Data and Second array Contain only -demopage: array Value.
status: "success",
-data: [
{
mid: "5",
name: "October 2014",
front_image: "http://www.truemanindiamagazine.com/webservice/magazineimage/frontimage/01.jpg",
title: "October 2014",
release_date: "2014-10-01",
short_description: "As the name suggest itself “Trueman India” will cover icons of India. Our national Magazine “Trueman India” is an expansion to our business, i",
current_issue: 0,
-demopage: [
{
link: "http://www.truemanindiamagazine.com/webservice/magazineimage/pageimage/2014/10/01-1413806104.jpg",
page_no: "1"
},
{
link: "http://www.truemanindiamagazine.com/webservice/magazineimage/pageimage/2014/10/2-1413806131.jpg",
page_no: "2"
},
{
link: "http://www.truemanindiamagazine.com/webservice/magazineimage/pageimage/2014/10/3-1413806170.jpg",
page_no: "3"
}
]
}
]
Here my main Dictionary Key is data i want data keey value in my One array and demopage key value in to another array here my two Array is self.imageArray and self.imagesa here my code For that
- (void)viewDidLoad
{
[super viewDidLoad];
[self.collectionView registerNib:[UINib nibWithNibName:#"CustumCell" bundle:nil] forCellWithReuseIdentifier:#"CellIdentifier"];
dispatch_async(kBgQueue, ^{
data = [NSData dataWithContentsOfURL: imgURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
-(void)fetchedData:(NSData *)responsedata
{
NSMutableArray *imagesArray = [[NSMutableArray alloc]init];
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.imageArray addObjectsFromArray:arr];
[self.storeTable reloadData];
}
self.storeTable.hidden=FALSE;
for (index=0; index<[self.imageArray count]; index++)
{
for(NSDictionary *dict in self.imageArray)
{
imagesArray = [dict valueForKey:#"demopage"];
self.imagesa = imagesArray;
}
NSLog(#"New Demo page array %#",self.imagesa);
}
}
then i get my data key value and it is ok but i got only last index means here my -data key Contain three -demopage key and i get only last -demopage key value i want all -demopage key value in to self.imagesa please give me solution for that.
also my Webservices link is Link
First get -data in NSMutableArray.
NSMutableArray *dataArray = [[NSMutableArray alloc]init];
NSMutableArray *imagesArray = [[NSMutableArray alloc]init];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
dataArray=[json objectForKey:#"data"];
for(NSDictionary *dict in dataArray )
{
imagesArray = [dict valueForKey:#"demopage"];
self.imagesa = imagesArray;
}
[selt.tableView reloadData];
You can give it a try like this:
NSError* error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
NSDictionary *dataDict = [json objectForKey:#"data"];
NSArray *imageArray = [dataDict objectForKey:#"demopage"];
self.imagesa = [NSMutableArray array];
for (NSDictionary *dict in array) {
NSString *imageUrl = [dict objectForKey:#"link"];
[self.imagesa addObject:imageUrl];
}
Then you got imageArray as dataSource for the collectionView.
I would use SBJson library, but not the last 4th version:
pod 'SBJson', '3.2'
Sample code, I changed variable names and formatting a little bit:
// Create a JSON String from NSData
NSData *responseData = [NSData new]; // Here you should use your responseData
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
if (! jsonString ) {
// Handle errors
}
// Create SBJsonParser instance
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
// Parse JSON String to dictionary
NSDictionary *jsonDic = [jsonParser objectWithString:jsonString];
// Get an array by key
NSArray *dicArray = [jsonDic objectForKey:#"demopage"];
// Reload collection view
if ( [dicArray count] > 0 ) {
dispatch_async(dispatch_get_main_queue(), ^{
// Reload Your Collection View Here and use dicArray (in your case imagesa array with dictionaries)
});
}
And when you set a cell, you can use something like this:
NSDictionary *dic = dicArray[indexPath.row];
NSString *link = dic[#"link"];
NSString *pageNo = dic[#"page_no"];

Nothing happens after calling [table reloadData] when called with dispatch_async

- (void) setRooms:(NSArray *)newRooms
{
NSLog(#"Main thread(cp3)... %d", [rooms count]);
rooms = newRooms;
[table reloadData];
NSLog(#"Main thread(cp4)... %d", [rooms count]);
}
- (void) parseJSONWithURL:(NSURL *)jsonURL
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSLog(#"Main thread(cp1)...%d", [rooms count]);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSLog(#"Background thread(cp1)...%d", [rooms count]);
NSError *error = nil;
// Request the data and store in a string.
NSString *resp = [NSString stringWithContentsOfURL:jsonURL
encoding:NSASCIIStringEncoding
error:&error];
// Convert the String into an NSData object.
NSData *data = [resp dataUsingEncoding:NSASCIIStringEncoding];
// Parse that data object using NSJSONSerialization without options.
NSDictionary *json = [[NSDictionary alloc] init];
json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
// Return to the main thread to update the UI elements
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"Main thread(cp2)...%d", [rooms count]);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[self setRooms:[json valueForKey:#"Rooms"]];
});
NSLog(#"Background thread(cp2)...%d", [rooms count]);
});
NSLog(#"Main thread(cp5)...%d", [rooms count]);
}
Try this
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSError *error = nil;
// Request the data and store in a string.
NSString *resp = [NSString stringWithContentsOfURL:jsonURL
encoding:NSASCIIStringEncoding
error:&error];
if (error == nil) {
// Convert the String into an NSData object.
NSData *data = [resp dataUsingEncoding:NSASCIIStringEncoding];
// Parse that data object using NSJSONSerialization without options.
NSDictionary *json = [[NSDictionary alloc] init];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
dispatch_sync(dispatch_get_main_queue(), ^{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
_rooms = [json valueForKey:#"Rooms"];
[_table reloadData];
});
}
});
or try
[self performSelectorOnMainThread:#selector(udpateAfterFetch:) withObject: [json valueForKey:#"Rooms"] waitUntilDone:YES];
-(void)udpateAfterFetch:(NSArray or whatever *) yourObject
{
_rooms = yourObject;
[_table reloadData];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
The table is not being reloaded because any UI update should happen in the main thread and it is not happening so in ur lines of code.

Resources