Question

I managed to install RestKit with cocoapods but now I'm confused with all the different classes it contains.

Let's say that i got the class:

@interface Actor : NSObject

@property (strong, nonatomic) NSString *firstName;
@property (strong, nonatomic) NSString *lastName;
@property (strong, nonatomic) NSNumber *age;

 @end

and that the url "http://SomeWebSite.com/actors" returns the json :

{
   Actors:
   [
      {
         "firstName": "Will",
         "lastName": "Ferrell",
         "age": 25
      },
      {
         "firstName": "Jim", 
         "lastName": "carrey",
         "age": 25
      } 
   ]
}

Can someone please give a complete example of how to get an array of persons with the data from the url?

Thanks alot!

Was it helpful?

Solution

Something like this:

    RKObjectMapping* actorMapping = [RKObjectMapping mappingForClass:[Actor class]];
    [actorMapping addAttributeMappingsFromDictionary:@{ 
        @"firstName": @"firstName",
        @"lastName": @"lastName",
        @"age": @"age",
      }];

    RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:actorMapping method:RKRequestMethodAny pathPattern:nil keyPath:@"Actors" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];

    NSURL *URL = [NSURL URLWithString:@"http://SomeWebSite.com/actors"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    RKObjectRequestOperation *objectRequestOperation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[ responseDescriptor ]];
    [objectRequestOperation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
        RKLogInfo(@"Load collection of Actors: %@", mappingResult.array);
    } failure:^(RKObjectRequestOperation *operation, NSError *error) {
        RKLogError(@"Operation failed with error: %@", error);
    }];

    [objectRequestOperation start];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top