POST JSON to Server from CoreData Information - ios

I'm somewhat new to iOS development so I'm trying to figure out posting a JSON string to a webserver and getting back some information. In the first page I ask for the user to give me their first name and last name. I then generate an ID for them and pass them to the second page. When the second page loads I want to send a JSON string to the server to tell it the users first name, last name among other things. The request would be like follows:
{
"user":{
"first_name":"Joe",
"last_name":"User",
"device_descriptor":"iPhone",
"idfa":"12345678",
"btmacid":"01:23:45:67:89:ab"
}
}
The create response successful would come back as follows:
{
"id": "8",
"first_name: "Joe",
"last_name": "User",
"device_descriptor": "iPhone",
"created_at": "2014-10-07T05:25:36.119Z",
"updated_at": "2014-10-07T05:25:36.119Z",
"idfa": "12345678",
"btmacid": "01:23:45:67:89:ab"
}
The code I have thus far is as follows:
#import "WelcomeViewController.h"
#import "CoreDataStack.h"
#import "UserInformation.h"
#import <CoreData/CoreData.h>
#import <RestKit/RestKit.h>
#interface WelcomeViewController ()
#property (nonatomic,strong) NSFetchedResultsController *fetchResultsController;
#property (strong, nonatomic) IBOutlet UILabel *welcomeTextLabel;
#end
#implementation WelcomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.fetchResultsController performFetch:nil];
UserInformation *entry = [[self.fetchResultsController fetchedObjects] objectAtIndex:0];
_welcomeTextLabel.text = [NSString stringWithFormat: #"Welcome " #"%#!", entry.firstName];
[self postUserInformation];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSFetchRequest *)entryFetchRequest{
NSFetchRequest *fetchReqeust = [NSFetchRequest fetchRequestWithEntityName:#"UserInformation"];
fetchReqeust.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"createdAt" ascending:NO]];
return fetchReqeust;
}
- (NSFetchedResultsController *)fetchResultsController {
if (_fetchResultsController != nil) {
return _fetchResultsController;
}
CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
NSFetchRequest *fetchRequest = [self entryFetchRequest];
_fetchResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:coreDataStack.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
return _fetchResultsController;
}
- (void) postUserInformation {
[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
[self.fetchResultsController performFetch:nil];
UserInformation *entry = [[self.fetchResultsController fetchedObjects] objectAtIndex:0];
RKObjectManager *manager = [RKObjectManager sharedManager];
RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[UserInformation class]];
NSDictionary *userInformation = #{
#"id" : #"userID",
#"first_name" : #"firstName",
#"last_name" : #"lastName",
#"device_descriptor" : #"deviceHardwareID",
#"created_at" : #"created_at",
#"updated_at" : #"updated_at",
#"idfa" : #"deviceAdvertisementID",
#"btmacid" : #"btmac_Id"
};
[responseMapping addAttributeMappingsFromDictionary:userInformation];
manager.requestSerializationMIMEType = RKMIMETypeJSON;
NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:responseMapping method:RKRequestMethodAny pathPattern:#"/users" keyPath:nil statusCodes:statusCodes];
RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];
[requestMapping addAttributeMappingsFromDictionary:userInformation];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping objectClass:[userInformation class] rootKeyPath:nil method:RKRequestMethodAny];
[manager addResponseDescriptor:responseDescriptor];
[manager addRequestDescriptor:requestDescriptor];
// NSDictionary *params = #{
// #"id" : entry.userID,
// #"first_name" : entry.firstName,
// #"last_name" : entry.lastName,
// #"device_descriptor" : entry.deviceHardwareID,
// #"created_at" : entry.createdAt,
// #"updated_at" : entry.updatedAt,
// #"idfa" : entry.deviceAdvertisementID,
// #"btmacid" : entry.btmacID
// };
[manager postObject:userInformation path:#"http://serverendpoint.com/users" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(#"Success");
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
Any help you all could provide would be greatly appreciated.

You shouldn't create the request mapping with
[requestMapping addAttributeMappingsFromDictionary:userInformation];
Because the inputs and outputs are the wrong way around. Instead, use the inverseMapping from your response mapping.

Related

IOS/Objective-C: Location pins (json) not showing up after application first launch

My app receives a json object the first time is executed (with three pin point locations); there is a mapKit (the first screen) and a TableView where the user can check those locations. The issue is that when I first launch the app, there are no pins on the map. But if I switch to the table I can see them - on the cells - and if I switch again to the map, the pins appear...I don't Know why this happens, shouldn't I see the pins right after the app launch? The Map code:
- (void)viewDidLoad {
[super viewDidLoad];
NSNotificationCenter *notification=[NSNotificationCenter defaultCenter];
[notification addObserver:self selector:#selector (receiveNotification:) name:#"notification" object:self];
_mapView.showsUserLocation=YES;
_mapView.showsBuildings=YES;
_locationManager = [[CLLocationManager alloc] init];
[_locationManager requestAlwaysAuthorization];
_mapView.delegate = self;
_locationManager.delegate=self;
}
-(void)viewDidAppear:(BOOL)animated{
[self receiveNotification:nil];
}
-(void)receiveNotification:(NSNotification*)notification{
NSArray *spots = [Spot spotType:#"users"];
NSArray *places = [Spot spotWithType:#"users"];
[_mapView addAnnotations:spots];
[_mapView addAnnotations:places];
}
And the table:
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.dataSource = self;
self.detailList=#[#"Your Favourite Spots",#"Our suggestion"];
}
-(void)viewDidAppear:(BOOL)animated{
_lisbonSpots = [[Spot spotType:#"users"]mutableCopy];
_users=[[Spot spotWithType:#"users"]mutableCopy];
[self.tableView reloadData];
}
EDIT - The Spot Class
#implementation Spot
#dynamic ID;
#dynamic name;
#dynamic desc;
#dynamic type;
#dynamic phone;
#dynamic latitude;
#dynamic longitude;
+ (instancetype)spotWithName:(NSString *)name andCoord:
(CLLocationCoordinate2D)coord type:(NSString*)type desc:(NSString*)desc phone:(NSString*)phone{
NSPersistentContainer *persistenceContainer = [AppDelegate sharedDelegate].persistentContainer;
NSManagedObjectContext *context = persistenceContainer.viewContext;
Spot *spot = [NSEntityDescription insertNewObjectForEntityForName:#"Spot" inManagedObjectContext:context];
spot.name = name;
spot.latitude = coord.latitude;
spot.longitude = coord.longitude;
spot.type=type;
spot.desc=desc;
spot.phone=phone;
[[AppDelegate sharedDelegate] saveContext];
return spot;
}
+ (instancetype)spotWithDict:(NSDictionary *)dict {
CLLocationCoordinate2D coord = CLLocationCoordinate2DMake([dict[#"latitude"] doubleValue], [dict[#"longitude"] doubleValue]);
return [Spot spotWithName:dict[#"name"] andCoord:coord type:dict[#"type"] desc:dict[#"desc"] phone:dict[#"phone"]];
}
+ (NSArray*)getSpotType:(NSString*)type withPredicate:(NSString*) pred andMessage:(NSString*)message {
NSPersistentContainer *persistenceContainer = [AppDelegate sharedDelegate].persistentContainer;
NSPredicate* predicate = [NSPredicate predicateWithFormat:pred, type];
NSManagedObjectContext *context = persistenceContainer.viewContext;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Spot"];
[request setPredicate:predicate];
NSError *error;
NSArray *result = [context executeFetchRequest:request error:&error];
if (error != nil) {
NSLog(message, [error localizedDescription]);
return nil;
}
return result;
}
+ (NSArray*)spotType:(NSString*)type {
return [Spot getSpotType:type withPredicate:#"type =%#" andMessage:#"[Spot spotType] -> %#"];
}
+ (NSArray*)spotWithType:(NSString*)type {
return [Spot getSpotType:type withPredicate:#"NOT (type = %#)" andMessage:#"[Spot spotWithType] -> %#"];
}
- (CLLocationCoordinate2D)coordinate {
return CLLocationCoordinate2DMake(self.latitude, self.longitude);
}
- (NSString *)title {
return self.name;
}
- (NSString *)description {
return [NSString stringWithFormat:#"%#", self.name];
}
#end
EDIT: The SpotService class
#implementation SpotService
+ (NSURL *)serviceURL {
return [NSURL URLWithString:#"http://training.reativ.io/ios/lisbon-spots"];
}
+ (BOOL)service:(id<SpotServiceInvoker>)invoker {
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:[SpotService serviceURL]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error != nil) {
NSLog(#"Response: %#", response);
NSLog(#"Error: %#", error);
return;
}
NSArray *lisbonSecrets = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
if ([invoker respondsToSelector:#selector(receiveSpot:)]){
[invoker receiveSpot:lisbonSecrets];
}
for(NSDictionary *dict in lisbonSecrets) {
[Spot spotWithDict:dict];
}
});
}];
[task resume];
return YES;
}
My guess is - your Spot class retrieve data asynchronously and when you call [Spot spotType:#"users"] for the first time from viewDidAppear on your MapView there is no data retrieved yet. When you switch view controller the data appears and the everything works smoothly.
But it's better to show us your Spot class. Probably your need a completion handler or something like this to achieve expected behaviour.
Also, you call addAnnotations every time when your map appears on the screen and it means that MKMapView will add a copy of the annotations each time your call this methods. It's better to add additional checks to be sure that you do not add the same annotations more than once.

Request Mapping in RestKit

https://github.com/RestKit/RestKit Only introduced mapping of JSON :
{
a : "a",
b : "b"
}
Mapping with Objective-C code:
RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];
[requestMapping addAttributeMappingsFromDictionary:#{#"entityId" : #"id"}];
But it do not show me how to mapping JSON Like:
{
entity: {
id: "xxxxxxxxx",
model : {
a : "a",
b : "b"
}
}
}
I did some attempt,
I create two model class like:
#interface Entity : NSObject
#property (strong, nonatomic) NSString *entityId;
#property (strong, nonatomic) NSObject *model;
#end
and
#interface Model : NSObject
#property (strong, nonatomic) NSString *a;
#property (strong, nonatomic) NSString *b;
#end
I make some RelationShipMapping Like ReponseMapping
RKObjectManager *objectManager = [RKObjectManager sharedManager];
RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];
[requestMapping addAttributeMappingsFromDictionary:#{#"entityId" : #"id"}];
RKObjectMapping *modelMapping = [RKObjectMapping requestMapping];
[modelMapping addAttributeMappingsFromDictionary:#{#"a" : #"b"}];
RKRelationshipMapping *modelToEntityMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:#"model" toKeyPath:#"model" withMapping:modelMapping];
[requestMapping addPropertyMapping:modelToEntityMapping];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping objectClass:[Entity class] rootKeyPath:nil method:RKRequestMethodAny];
[objectManager addRequestDescriptor:requestDescriptor];
the following code I create the object
Entity *entity = [Entity new];
entity.entityId = #"/example/entityId";
Model *exampleModel = [ExampleModel new];
exampleModel.a = #"a";
exampleModel.b = #"b";
entity.model = exampleModel;
But I log the post JSON on my server:
{ id: '/example/entityId', 'model[a]': 'a', 'model[b]': 'b' }
So how to make a relationship when use requestMapping?

Access Data step count from Health app of Apple

I would like to show in my app a label of my step count
The data step count will be take from the health app of apple but i don't know if will be possible
how i can print the value of my step count in a label ?
This is my code
Thanks
#import "ViewController.h"
#import HealthKit;
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
if(NSClassFromString(#"HKHealthStore") && [HKHealthStore isHealthDataAvailable])
{
HKHealthStore *healthStore = [[HKHealthStore alloc] init];
NSSet *shareObjectTypes = [NSSet setWithObjects:
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass],
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight],
nil];
NSSet *readObjectTypes = [NSSet setWithObjects:
[HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth],
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount],
nil];
[healthStore requestAuthorizationToShareTypes:shareObjectTypes
readTypes:readObjectTypes
completion:^(BOOL success, NSError *error) {
if(success == YES)
{
// Set your start and end date for your query of interest
NSDate *startDate, *endDate;
// Use the sample type for step count
HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
_stepLabel.text = [NSString stringWithFormat:#"%#",HKQuantityTypeIdentifierStepCount];
// Create a predicate to set start/end date bounds of the query
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate];
// Create a sort descriptor for sorting by start date
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:YES];
HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType
predicate:predicate
limit:HKObjectQueryNoLimit
sortDescriptors:#[sortDescriptor]
resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
NSLog(#"%# ", results);
if(!error && results)
{
for(HKQuantitySample *samples in results)
{
// your code here
}
}
}];
// Execute the query
[healthStore executeQuery:sampleQuery]; }
else
{
// Determine if it was an error or if the
// user just canceld the authorization request
}
}];
}}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Yes, you can read the step count from HealthKit if the user grants permission for your app to do so.
See the HealthKit documentation:
https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HealthKit_Framework/index.html#//apple_ref/doc/uid/TP40014707

CoreData with RestKit

Try to implement usage of CoreData with RestKit.
Problem - got message I restkit.core_data:RKInMemoryManagedObjectCache.m:94 Caching instances of Entity 'ItemRK' by attributes 'itemID' and crash. Try to add Exception on errors- cant catch it.
Check mapping - OK;
Check DBModel - OK; empty DB created successfully
I cant understand what was done wrong and where, so I put here main parts of code (sorry for long explanation).
What was done:
I try to organize my code like proposed here.
So i create RKBaseObjectManager for using RestKit
#implementation RKBaseObjectManager
#pragma mark - Public
+ (instancetype)sharedManager
{
RKBaseObjectManager *sharedManager = [self managerWithBaseURL:[NSURL URLWithString:kBaseApiUrl]];
sharedManager.requestSerializationMIMEType = RKMIMETypeJSON;
[sharedManager setupRequestDescriptor];
[sharedManager setupResponseDescriptor];
[sharedManager setupCoreDataWithRKObjectManager:sharedManager];
return sharedManager;
}
- (void)setupRequestDescriptor { }
- (void)setupResponseDescriptor { }
#pragma mark - Private
- (void)setupCoreDataWithRKObjectManager:(RKObjectManager *)manager
{
NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];
manager.managedObjectStore = managedObjectStore;
[managedObjectStore createPersistentStoreCoordinator];
NSString *dbName = [NSString stringWithFormat:#"%#.sqlite", kDataBaseName];
NSString *storePath = [RKApplicationDataDirectory() stringByAppendingPathComponent:dbName];
NSError *error;
NSPersistentStore *persistentStore = [managedObjectStore
addSQLitePersistentStoreAtPath:storePath
fromSeedDatabaseAtPath:nil
withConfiguration:nil
options:#{NSMigratePersistentStoresAutomaticallyOption : #YES, NSInferMappingModelAutomaticallyOption: #YES}
error:&error];
NSAssert(persistentStore, #"Failed to add persistent Store with error - %#", error.localizedDescription);
[managedObjectStore createManagedObjectContexts];
managedObjectStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:managedObjectStore.persistentStoreManagedObjectContext];
}
#end
Then for each entity create inherited class with singleton - ItemManager
#implementation ItemManager
#pragma mark - Singleton
+ (instancetype)sharedManager
{
static ItemManager *sharedManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^ {
sharedManager = [super sharedManager];
});
return sharedManager;
}
#pragma mark - Public
- (void)loadItemWithId:(NSInteger)itemId success:(ObjectSuccess)success failure:(ObjectFailure)failure
{
NSDictionary *parameters = #{ #"item_id" : #(itemId) };
[self getObjectsAtPath:kItemsDetailsPathPattern parameters:parameters success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
if (success) {
success(mappingResult.array);
}
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
if (failure) {
failure (operation, error);
}
}];
}
#pragma mark - Private
- (void)setupResponseDescriptor
{
[super setupResponseDescriptor];
NSIndexSet *statusCode = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);
RKResponseDescriptor *itemDescriptor = [RKResponseDescriptor
responseDescriptorWithMapping:[MappingProvider mappingForItemRKEntity]
method:RKRequestMethodGET
pathPattern:kItemsDetailsPathPattern
keyPath:nil
statusCodes:statusCode];
[self addResponseDescriptor:itemDescriptor];
}
#end
For mapping I add next class - MappingProvider
#implementation MappingProvider
#pragma mark - EntityMapping
+ (RKEntityMapping *)mappingForItemRKEntity
{
RKEntityMapping *itemEntityMapping = [RKEntityMapping mappingForEntityForName:MPItemEntityName inManagedObjectStore:[RKBaseObjectManager sharedManager].managedObjectStore];
itemEntityMapping.identificationAttributes = #[#"itemID"];
[itemEntityMapping addAttributeMappingsFromDictionary:[self mappingDictionaryForItem]];
return itemEntityMapping;
}
+ (RKObjectMapping *)mappingForItemRK
{
RKObjectMapping *itemMapping = [RKObjectMapping mappingForClass:[ItemRK class]];
[itemMapping addAttributeMappingsFromDictionary:[self mappingDictionaryForItem]];
return itemMapping;
}
#pragma mark - Private
+ (NSDictionary *)mappingDictionaryForItem
{
NSDictionary *dictionary = #{
#"item_id" : #"itemID",
#"name" : #"name",
#"description" : #"itemDescription",
#"type" : #"type",
#"level" : #"level",
#"rarity" : #"rarity",
#"vendor_value" : #"vendorValue",
#"icon_file_id" : #"iconFileId",
#"icon_file_signature" : #"iconFileSignature",
#"default_skin" : #"defaultScin"
};
return dictionary;
}
And when I want to get object -
[[ItemManager sharedManager] loadItemWithId:28445 success:^(NSArray *mappingResult) {
ItemRK *result = (ItemRK *)[mappingResult firstObject];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Fail to load - %#", error.localizedDescription);
}];
Test entity class (autoGenerated)
#interface ItemRK : NSManagedObject
#property (nonatomic, retain) NSNumber * defaultScin;
#property (nonatomic, retain) NSNumber * flags;
#property (nonatomic, retain) NSData * gameTypes;
#property (nonatomic, retain) NSNumber * iconFileId;
#property (nonatomic, retain) NSString * iconFileSignature;
#property (nonatomic, retain) NSString * itemDescription;
#property (nonatomic, retain) NSNumber * itemID;
#property (nonatomic, retain) NSNumber * level;
#property (nonatomic, retain) NSString * name;
#property (nonatomic, retain) NSString * rarity;
#property (nonatomic, retain) NSData * restrictions;
#property (nonatomic, retain) NSString * type;
#property (nonatomic, retain) NSNumber * vendorValue;
#property (nonatomic, retain) WeaponRK *weapon;
#end
So the problem is as I wrote at beggining - something with core_data:RKInMemoryManagedObjectCache. Also try to found similar problems:
To many unique keys added - not the reason - I use only one itemEntityMapping.identificationAttributes = #[#"itemID"];
To many request - not the reason - only one request;
API for my example - https://api.guildwars2.com/v1/item_details.json?item_id=28445 - checked with Postman - OK.
So think I was wrong somewhere in mapping and combining it to CoreData - but cant find where.
Question - where i make mistake? Why i cant combine RestKit and CoreData?
Finally found the reason -
When I create ItemManager I also automatically try to add response descriptor (with this method setupResponseDescriptor), last use mapping, and mapping use 'BaseObjectManager' as it managedObjectStore the is a parent for ItemManager. So during creating ItemManager I create infinity cycle - as result program crashed.
Solution - I create response descriptor in class where I call ItemManager like
[[ItemManager sharedManager] addResponseDescriptor:[ResponseDescriptorProvider itemResponseDescriptor]];
[[ItemManager sharedManager] loadItemWithId:28450 success:^(NSArray *result) {
NSArray *arout = result;
NSLog(#"Result: Item - %# and nested Weapon - %#", (ItemRK *)[arout firstObject], ((WeaponRK *)((ItemRK *)[arout firstObject]).weapon).type );
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Error response': %#", error);
}];
Also i moved out response descriptor from manager to separate class - ResponseDescriptorProvider
+ (RKResponseDescriptor *)itemResponseDescriptor
{
RKResponseDescriptor *responseDescriptor =
[RKResponseDescriptor responseDescriptorWithMapping:[MappingProvider mappingForItemRKEntity]
method:RKRequestMethodGET
pathPattern:kItemsDetailsPathPattern
keyPath:nil
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
return responseDescriptor;
}
The rest leave the same.
Thanks all for help.

RestKit: per-request object mapping when using [[RKClient sharedClient] post: usingBlock:]

I need to POST a video to a server in the background. Until now i've been using this sort of pattern when POSTing:
- (BOOL)loginUser:(user *)user
{
BOOL ret = NO;
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.waitView startWithMessage:#"Signing in ..."];
[self.objectManager postObject:user usingBlock:^(RKObjectLoader *loader)
{
loader.delegate = self;
loader.targetObject = nil;
loader.objectMapping = [RKObjectMapping mappingForClass:[user class] usingBlock:^(RKObjectMapping *mapping)
{
[mapping mapKeyPath:#"id" toAttribute:#"ID"];
[mapping mapKeyPath:#"last_name" toAttribute:#"last_name"];
[mapping mapKeyPath:#"first_name" toAttribute:#"first_name"];
[mapping mapKeyPath:#"middle_name" toAttribute:#"middle_name"];
[mapping mapKeyPath:#"email" toAttribute:#"email"];
[mapping mapKeyPath:#"password" toAttribute:#"password"];
[mapping mapKeyPath:#"authentication_token" toAttribute:#"authentication_token"];
}];
loader.serializationMapping = [loader.objectMapping inverseMapping];
loader.serializationMapping.rootKeyPath = NSStringFromClass([user class]);
}];
return ret;
}
... but this pattern doesn't seem to let me access any RKRequest object on which to set the backgroundPolicy. So, i've looked at using RKClient like so:
- (BOOL)postBigMediaFile:(NSString *)pathToBigFile
{
BOOL ret = NO;
NSString *resourcePath = #"/bigFile";
[[RKClient sharedClient] post:resourcePath usingBlock:^(RKRequest *request)
{
request.backgroundPolicy = RKRequestBackgroundPolicyContinue;
// how do I set up the object mapping?
}];
return ret;
}
... but the RKRequest object doesn't seem to have a way of accessing an RKObjectLoader for which to setup the mapping on. How do I post data in the background using object mapping?
Silly me ... RKObjectLoader is a subclass of RKRequest, so I can just do loader.backgroundPolicy = ... :-)

Resources