Search code examples
iosobjective-cjsonuitableviewafnetworking

AFNetworking 3.0 GET request save into class in iOS


After searching the internet for how to use AFNetworking 3.0 to save the response object inside a custom class, all that I found is the basic usage of AFNetworking library with GET requests such as GET request using AFNetworking and saving response and AFNetworking send array in JSON parameters of GET request.

Code:

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

listOfEventsObjects = [@[] mutableCopy];
self.tableView.delegate = self;


AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

[manager GET:@"http://api.com.getevents.php" parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {


    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSArray *h  = [responseObject objectForKey:@"events"];

    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:h options:0 error:&error];
    NSArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];


    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

    for (int i  = 0 ; i < [json count]; i++) {
        geeksEvent *h1 = [geeksEvent new];

        //h1.eventId = [];
        //h1.eventId = [[json valueForKey:@"eventId"] intValue];
        //NSLog(@"json data is: %@",h1);

    }

    //  events = [responseObject objectForKey:@"events"];

    if ([responseObject isKindOfClass:[NSArray class]]) {
      //  NSArray *responseArray = responseObject;
        NSLog(@"array");
        /* do something with responseArray */
    } else if ([responseObject isKindOfClass:[NSDictionary class]]) {
        NSLog(@"dictionary");
        NSDictionary *responseDict = responseObject;

      //  NSDictionary *responseDict = responseObject;
        /* do something with responseDict */
    }


//        AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
//
//        responseSerializer = [AFJSONResponseSerializer serializer];
//        responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json; charset=UTF-8", nil];
//    
//       // NSArray *data  = (responseObject *) NSArray;
//        NSError *error;
//        NSData *data   = (NSData *) responseObject;
//       // NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:errno error:&error];
//    
//        
//        NSLog(@"JSon arrays is: %@",data);

        //NSDictionary *jsonDict = (NSDictionary *) responseObject;

//        
//        NSLog(@"%lu",(unsigned long)events.count);
//        
//        for (int i =  0; i  <  [events count]; i ++) {
//            
//            geeksEvent *event  = [events objectAtIndex:i];
//        
//            
//            NSLog(@"event %d is %@",i,event);
//            
//            
//            @try {
//                
//                event.eventId = [[events valueForKey:@"eventId"]intValue];
//                
//                event.eventTitle  = [[events valueForKey:@"eventTitle"] componentsJoinedByString:@""];
//                
//                event.eventShortDiscription = [[event valueForKey:@"eventShortDesc"] componentsJoinedByString:@""];
//                event.eventDescription = [[event valueForKey:@"eventDescription"] componentsJoinedByString:@""];
//                
//                event.eventDate = [events valueForKey:@"eventDate"];
//                event.eventTime = [events valueForKey:@"eventTime"];
//                event.eventUrl = [events valueForKey:@"eventUrl"];
//                
//                [listOfEventsObjects addObject:event];
//                
//            } @catch (NSException *exception) {
//                
//                NSLog(@"%@",exception);
//                
//            } @finally {
//                
//            }
//            
//        }


        [self.tableView reloadData];

I cannot figure out how to save the response object into custom class.

geeksEvent ## custom class:

.h

#import <Foundation/Foundation.h>

@interface GeeksLocations : NSObject
@property (nonatomic) int geeksBranchId;
@property(nonatomic) double *geeksLongtitude;
@property (nonatomic) double *geeksLatitude;
@property (nonatomic,strong) NSString *geeksAddress;
@property (nonatomic,strong) NSString *geeksMobile;
@property (nonatomic,strong) NSString *geeksTel;
@property (nonatomic,strong) NSString *geeksOpenDays;
@property (nonatomic,strong) NSDate *geeksOpenTime;

@end

.m

#import "GeeksLocations.h"

@implementation GeeksLocations
@synthesize geeksBranchId;
@synthesize geeksLongtitude;
@synthesize geeksLatitude;
@synthesize geeksMobile;
@synthesize geeksTel;
@synthesize geeksAddress;
@synthesize geeksOpenDays;
@synthesize geeksOpenTime;
@end

Response

{"success":1,"events":[{"eventId":"1","eventTitle":"Open Wings Tuesday","eventShortDesc":"we are offering open wings all the day","eventDiscription":null,"eventDate":"2016-05-22","eventTime":"12:49:00","eventUrl":"http://www.code-bee.net/geeks/images/cover-7.jpg"},{"eventId":"2","eventTitle":"Testing","eventShortDesc":"Testing","eventDiscription":null,"eventDate":"2016-05-22","eventTime":"12:49:00","eventUrl":"http://www.code-bee.net/geeks/images/cover-8.jpg"}]


Solution

  • Add all events to an array, you will then have an array of dictionaries. Also make a new array which will hold your new instances. Now:

    for (NSDictionary *dictionary in myArrayContainingAllEvents){
        GeeksLocation *location = [GeeksLocation alloc] initWithDictionary:dictionary]; 
        [newArrayForInstances addObject: location];
    }
    

    In the GeeksLocation class add the following initializer:

    -(instanceType)initWithDictionary: (NSDictionary *) dictionary{ 
         self = [super init];
         if(self){
                self.geeksAddress = [dictionary objectForKey:address];
                self.....         = [dictionary objectForKey:.......];
         }
    
    
         return self;
    }
    

    Hope this helps