Show JSON in tableview IOS Xcode [closed] - ios

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Dear fellow programmers.
I have to connect to an api and use the json I get back to store it in a table.
Using AFnetworking, Xcode and ios.
So far it has been taing me a full day and drives me insane. I've tried several tutorials and projects but I just can't get it to work.
The first problem is I cant seem to find my key in the json that I get back..
Of course I have to parse the json, which does not really work for me either
Can you please help me get my json into a table view?
The api I use is : https://api.9292.nl/0.1/locations?lang=nl-NL&q=amsterd
The json I recieve in the app as output is
{
"locations": [
{
"id": "station-amsterdam-centraal",
"type": "station",
"stationId": "asd",
"stationType": "Station",
"name": "Amsterdam Centraal",
"place": {
"name": "Amsterdam",
"regionCode": "NH",
"regionName": "Noord-Holland",
"showRegion": false,
"countryCode": "NL",
"countryName": "Nederland",
"showCountry": false
},
"latLong": {
"lat": 52.378706,
"long": 4.900489
},
"urls": {
"nl-NL": "/station-amsterdam-centraal",
"en-GB": "/en/station-amsterdam-centraal"
}
etc
The code I have right now is:
//
// ViewController.m
// 9292apiconnection
//
// Created by TheDutchBeast on 02-09-14.
// Copyright (c) 2014 Lambregts. All rights reserved.
//
#import "ViewController.h"
#import <AFNetworking/AFNetworking.h>
#interface ViewController ()
#property (strong, nonatomic) NSDictionary *posts;
#property (strong, nonatomic) NSMutableArray *post;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://api.9292.nl/0.1/locations?lang=nl-NL&q=amsterd" parameters:nil success:^(
AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Please help me define the key from the json code and how to get these values into a table in Xcode , ios
. Only ID and NAME needs to be shown in the table
Please no links to tutorials, since I have seen them all
Thanks in advance

try this convert the response json into NSDictionary
NSDictionary *receivedDataDic = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:kNilOptions error:&error];
now access the values which you want by using key names , like
NSString * id = [receivedDataDic valueForKey:#"id"];
NSString * name = [receivedDataDic valueForKey:#"name"];
use those variables where you want
make these changes in your code
#interface ViewController ()
{
NSString * id ,* name;
}
#property (strong, nonatomic) NSDictionary *posts;
#property (strong, nonatomic) NSMutableArray *post;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://api.9292.nl/0.1/locations?lang=nl-NL&q=amsterd" parameters:nil success:^(
AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *receivedDataDic = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:kNilOptions error:&error];
id = [receivedDataDic valueForKey:#"id"];
name = [receivedDataDic valueForKey:#"name"];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}

When using AFNetworking, the response object is an NSDictionary Object, there is no need to convert to an NSDictionary
you should be able to parse the locations array like this.
AFHTTPRequestOperationManager *manager =
[AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:#"http://api.9292.nl/0.1/locations?lang=nl-NL&q=amsterd"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *locations = [responseObject objectForKey:#"locations"];
for (id obj in locations) {
NSLog(#"id: %#, name: %#", [obj objectForKey:#"id"],
[obj objectForKey:#"name"]);
}
}
failure:^(AFHTTPRequestOperation *operation,
NSError *error) { NSLog(#"Error: %#", error); }];

Related

JSON parsing with AFNetworking and model Class

I am bit confused in fetching data and displaying data from json into my App using Model.
I am having this kind of json data :
{
result
[
{
key : value
key : value
key : value
}
{
key : value
key : value
key : value
}
]
}
I am trying this kind of code:
json = [[NSMutableArray alloc]init];
NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:&writeError];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&writeError];
json = dic[#"Result"];
int i;
for (i = 0; i <= json.count; i++)
{
NSMutableArray *array = json[i];
[json enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL *stop)
{
// Dim = [[DimEntityFull alloc]initWithJSONDictionary:obj];
saveSearch = [[SaveSearchMaster alloc]initWithJSONDictionary:obj];
} ];
}
I am using "AFNetworking" and I am trying to fetch data and store into model class and then display to custom cell labels.
How can I get it.
Thank You.
In your view controller
- (void)viewDidLoad
{
[super viewDidLoad];
[self getUsersList];
}
-(void)getUsersList
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
[manager POST:[NSString stringWithFormat:#"http://www.yourdomainname.com/getUserList"] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
//we will add Modal class objects of users in this array
usersArray=[[NSMutableArray alloc]init];
//getting result dictionary from response
NSDictionary *resultDictinary = [responseObject objectForKey:#"result"];
for (NSDictionary *userDictionary in resultDictinary)
{
//allocating new user from the dictionary
User *newUSer=[[User alloc]initWithDictionary:userDictionary];
[usersArray addObject:newUSer];
}
//in users array, you have objects of User class
//reload your tableview data
[self.TableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
Now Create New file Called 'User'
in User.h
#interface User : NSObject
{
NSString *userID;
NSString *firstName;
NSString *lastName;
}
#property (nonatomic, retain)NSString *userID;
#property (nonatomic, retain)NSString *firstName;
#property (nonatomic, retain)NSString *lastName;
-(id)initWithDictionary:(NSDictionary *)sourceDictionary;
#end
in User.m
#import "User.h"
#implementation User
#synthesize userID,firstName,lastName;
-(id)initWithDictionary:(NSDictionary *)sourceDictionary
{
self = [super init];
if (self != nil)
{
self.firstName=[sourceDictionary valueForKey:#"firstName"];
self.lastName=[sourceDictionary valueForKey:#"lastName"];
self.userID=[sourceDictionary valueForKey:#"userID"];
}
return self;
}
#end
in your numberOfRowsInSectionmethod
return usersArray.count;
in your cellForRowAtIndexPath method
User *user=(User *)[usersArray objectAtIndex:indexPath.row];
yourLabel.text=user.firstName;

afnetworking get json data out from response

I am trying to extract data(just a string) from request and set it to the NSString. I tried it in many way but it is not working. If anyone can point out my mistake, it will be very helpful for me.
json data
{
"status": 1,
"key": "1e39248f4a5e05153dc376a"
}
My code
NSString *key;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = # {#"app_token" :APP_TOKEN};
[manager POST:GET_USER_KEY_URL parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary* response = (NSDictionary*) responseObject;
key=[response valueForKey:#"key"];
[[NSUserDefaults standardUserDefaults]setValue:(key) forKey:USER_KEY];
NSLog(#"NEW KEY Request: %#", key);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"NEW KEY Request error: %#", error);
}];
Just want to assign response "key" data and store it on the NSString *key;
Thank you in advance.
You have declared the variable key outside of the block. You need to add __block infront of NSString *key;
To assign a variable outside a block you have to remember the __block specifier.
Related question:
Assign a variable inside a Block to a variable outside a Block

Unable to Save AFNetworking responseObject

I'm calling a web service using AFNetworking and saving the return data in NSDictionary object. But nothing's being stored in it, even when data is successfully logged in NSLog().
This is my dictionary:
#property (strong, nonatomic) NSDictionary *newsItems;
and this is my codes:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"key": #"keyy", #"q": #"ads" };
[manager POST:BaseURLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.newsItems = (NSDictionary *) responseObject;
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
First, check whether you're getting any response from web service using the below line:
NSLog(#"RESPONSE : %#", operation.responseString);
Second, if your web service is supposed to return an array of dictionaries, then you should declare an array instead on dictionary.
#property (strong, nonatomic) NSArray *newsItems;
instead of
#property (strong, nonatomic) NSDictionary *newsItems;
You need to declare an NSArray & not NSDictionary like following:
#property (strong, nonatomic) NSArray *newsItems;
And assign responseObject like following:
self.newsItems = (NSArray *) responseObject;
Hope this helps.

Issue with AFNetworking

My client webservice send me a result like this:
{"login":{"EMAIL":"none","ID":"none","NOME":"none"}}
So, in AFN doesn't work.
But, if have one more result works:
{"login":[{"EMAIL":"none","ID":"none","NOME":"none"},{"EMAIL":"none","ID":"none","NOME":"none"}]}
My code:
NSDictionary *paramLogin = [NSDictionary dictionaryWithObjectsAndKeys:_txtEmail.text, #"email",_txtSenha.text, #"senha", nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://webservice.info" parameters:paramLogin success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#" , responseObject );
for (NSDictionary *retLogin in [responseObject valueForKeyPath:#"login"]) {
nome = [retLogin objectForKey:#"nome"];
email = [retLogin objectForKey:#"email"];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
why it is like this? or what I've to do ?
Sometimes [responseObject valueForKeyPath:#"login"] returns and array, sometimes it returns a dictionary. You need to test for this.
id loginValue = [responseObject valueForKeyPath:#"login"];
if ([loginValue isKindOfClass:[NSDictionary class]]) {
nome = [loginValue objectForKey:#"nome"];
email = [loginValue objectForKey:#"email"];
} else if ([loginValue isKindOfClass:[NSArray class]]) {
for (NSDictionary *retLogin in [responseObject valueForKeyPath:#"login"]) {
nome = [retLogin objectForKey:#"nome"];
email = [retLogin objectForKey:#"email"];
}
} else {
// ERROR: Unexpected value
}
When you have 1 value, then loginValue is an NSDictionary. It contains {"EMAIL":"none","ID":"none","NOME":"none"}.
When you have more than 1 value, then loginValue is an NSArray. The array contains [<NSDictionary>, <NSDictionary>]. Each of of these dictionaries contains {"EMAIL":"none","ID":"none","NOME":"none"}.
Problem is with your json data structure. It's not consistent.
{"login":{"EMAIL":"none","ID":"none","NOME":"none"}}
Here [responseObject valueForKeyPath:#"login"] is a single NSDictionary object.
But here,
{"login":[{"EMAIL":"none","ID":"none","NOME":"none"},{"EMAIL":"none","ID":"none","NOME":"none"}]}
Here [responseObject valueForKeyPath:#"login"] is an NSArray. So your fast enumeration works.
Best solution is to ask your webservice developer to send an array all the time, even 'login' has a single object. so it should look like this,
{"login": [{"EMAIL":"none","ID":"none","NOME":"none"}]} //notice square brackets
Otherwise you have to modify your code to check for an NSDictionary instead of array when there's only one object.
I suspect the issue is that you aren't retaining the AFHTTPRequestOperationManager object.
Assuming this code is in something like viewDidAppear:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:...];
Then manager will be destroyed before it has a chance to complete.
Instead add a property and store the manager object in that:
#interface MyViewController ()
#property (nonatomic) AFHTTPRequestOperationManager *manager;
#end
and use:
self.manager = [AFHTTPRequestOperationManager manager];
[self.manager GET:...];
if you are getting response like that than use below code
NSMutableArray *category = [[NSMutableArray alloc]init];
category = [responseObject objectForKey:#"login"];
for(int i = 0; i < [category count]; i++)
{
NSDictionary *dic = [category objectAtIndex:i];
nome = [dic objectForKey:#"nome"];
email = [dic objectForKey:#"email"];
}

iOS Retrieving valueForKey?

I'm new to iOS and working on a basic app, it's currently working with SSKeychain and AFNetworking to interact with an API. When you log in with the app I retrieve and set the auth_token in my CredentialStore class, I need to send the auth token to the API as a http header to get access. How can I retrieve the token that I'm storing in the CredentialStore class in my HomeViewController.
Here is my CredentialStore:
#import "GFCredentialStore.h"
#import "SSKeychain.h"
#define SERVICE_NAME #"Groupify"
#define AUTH_TOKEN_KEY #"auth_token"
#implementation GFCredentialStore : NSObject
- (BOOL)isLoggedIn {
return [self authToken] != nil;
}
- (void)clearSavedCredentials {
[self setAuthToken:nil];
}
- (NSString *)authToken {
return [self secureValueForKey:AUTH_TOKEN_KEY];
}
- (void)setAuthToken:(NSString *)authToken {
[self setSecureValue:authToken forKey:AUTH_TOKEN_KEY];
[[NSNotificationCenter defaultCenter] postNotificationName:#"token-changed" object:self];
}
- (void)setSecureValue:(NSString *)value forKey:(NSString *)key {
if (value) {
[SSKeychain setPassword:value
forService:SERVICE_NAME
account:key];
} else {
[SSKeychain deletePasswordForService:SERVICE_NAME account:key];
}
}
- (NSString *)secureValueForKey:(NSString *)key {
return [SSKeychain passwordForService:SERVICE_NAME account:key];
}
#end
Here I am trying to retrieve the authToken value and set it to a string so that I can send it as a http header:
#import "GFHomeViewController.h"
#import <AFNetworking.h>
#import "GFCredentialStore.h"
#define kBaseURL "http://localhost:3000/"
#define kHomeURL "newsfeed.json"
#interface GFHomeViewController ()
#end
#implementation GFHomeViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
__weak typeof(self)weakSelf = self;
NSString *urlString = [NSString stringWithFormat:#"%s%s", kBaseURL, kHomeURL];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue: forHTTPHeaderField:#"auth_token"];
[manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
Assuming SSKeychain is saving and returning values to/from the keychain, I'd think you would simply be able to do something like this
GFCredentialStore *credentialStore = [[CGCredentialStore alloc] init];
if ([credentialStore isLoggedIn]) {
NSString *authToken = [credentialStore authToken];
[manager.requestSerializer setValue:authToken forHTTPHeaderField:#"auth_token"];
} else {
// prompt/display controller for login
}
If I'm missing something in your problem/issue you're having, please clarify your question, and I'll have another go at it.

Resources