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.
Related
So when using "AFNetworking" in my project, i tried the very basic examples just to make sure it's working but i keep getting the following error:
[NSConcreteMutableData appendData:]: message sent to deallocated instance 0x83aa8030
My code is:
NSDictionary *params = #{#"username": username,
#"password": password,
#"comment_id": comment_id]};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager POST:url parameters:params progress:nil success:^(NSURLSessionTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(NSURLSessionTask * _Nullable operation, NSError * _Nonnull error) {
NSLog(#"Error: %#", error);
}];
The error occurs in the following function which is part of script: ([AFURLSessionManagerTaskDelegate URLSession:dataTask:didReceiveData:] AFURLSessionManager.m:262)
#pragma mark - NSURLSessionDataDelegate
- (void)URLSession:(__unused NSURLSession *)session
dataTask:(__unused NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data{
self.downloadProgress.totalUnitCount = dataTask.countOfBytesExpectedToReceive;
self.downloadProgress.completedUnitCount = dataTask.countOfBytesReceived;
[self.mutableData appendData:data];}
Try to store an instance of AFHTTPSessionManager in your class as a property. Something like:
#property (nonatomic, strong) AFHTTPSessionManager *manager;
Then you should not see an error about the deallocated object, hopefully!
Else please post more context to the problem, so that I can help you with this.
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;
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
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); }];
So I'm trying to use [RKObjectManager postObject:path:parameters:success:failure:] but am having some trouble getting it working with my login POST request. For some reason I keep getting a response back from my server saying that the parameters for email and password are required, even though I'm passing the following dictionary in for parameters:
NSDictionary *params = #{#"email": #"fakeEmail#fakeDomain.com, #"password": #"test123!"};
When I log out the RKObjectRequestOperation it doesn't show any parameters on the request. Do I have to pass an object in with the request? If so, what object would I pass in?
(Previously I was just using and AFJSONRequestOperation, but I would like to update the app to use RestKit and take advantage of the easy object mapping it provides).
Any help would be appreciated.
EDIT With More Code:
I have a subclass of RKObjectManager called UserAuthService, using RKMIMETYPEJSON as the requestSerializationMIMEType, with the following request descriptor setup:
// User
RKResponseDescriptor *userResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:[UserAuthMappingProvider userMapping]
method:RKRequestMethodPOST
pathPattern:#"user/login"
keyPath:#"response.users"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[self addResponseDescriptor:userResponseDescriptor];
The method I'm using to actually request is:
- (void)logUserInWithEmail:(NSString *)email andPassword:(NSString *)password success:(void (^)(UserObject *))success failure:(void (^)(RKObjectRequestOperation *, NSError *))failure
{
// Request Params
NSDictionary *params = #{#"email": email, #"password": password};
NSLog(#"Params: %#", params);
[self postObject:nil path:#"user/login" parameters:params
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult){
if (success)
{
NSArray *userArray = [mappingResult array];
success([userArray firstObject]);
}
}
failure:^(RKObjectRequestOperation *operation, NSError *error){
NSLog(#"Error: %#", error);
if (failure)
{
failure(operation, error);
}
}];
}
the userMapping method in UserAuthMappingProvider looks like this:
+ (RKEntityMapping *)userMapping
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
RKEntityMapping *userMapping = [RKEntityMapping mappingForEntityForName:#"User" inManagedObjectStore:appDelegate.managedObjectStore];
userMapping.identificationAttributes = #[ #"uuid" ];
[userMapping addAttributeMappingsFromDictionary:#{#"email": #"email",
#"first_name": #"firstName",
#"last_name": #"lastName",
#"is_logged_in": #"isLoggedIn",
#"site_id": #"siteID",
#"user_name": #"username",
#"uuid": #"uuid"}];
return userMapping;
}
and the UserObject (with each set to #dynamic in the .m):
#interface UserObject : NSManagedObject
#property (strong, nonatomic) NSString *email;
#property (strong, nonatomic) NSString *firstName;
#property (strong, nonatomic) NSString *lastName;
#property (assign, nonatomic) BOOL isLoggedIn;
#property (strong, nonatomic) NSNumber *siteID;
#property (strong, nonatomic) NSString *username;
#property (strong, nonatomic) NSString *uuid;
#end
The error I'm getting back is:
Error Domain=org.restkit.RestKit.ErrorDomain Code=-1011 "Expected status code in (200-299), got 400" UserInfo=0x8eadbf0 {NSLocalizedRecoverySuggestion={"required_parameters":{"email":"string","password":"string"},"status":"failed","message":"Insufficient information passed. see 'required_parameters'"}
Basically my goal is to take the success response of the user/login call and map it to the UserObject.
Finally figure it out, and of course it was a really stupid issue. The server was expecting a dictionary of params, but my object manager's requestSerializationMIMEType was set to RKMIMETypeJSON. So, once I commented that line out the request worked fine with the object being nil and the parameters being set to a dictionary of #{#"email": email, #"password": password}