EzDevInfo.com

restkit

an HTTP resource kit for Python Welcome to RESTKit’s documentation! — restkit 4.2.2 documentation

RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class

I ran into a new problem that I can't seem to find a way around... Here is my RestKit code, following the Twitter Core Data example:

//
// RESTKIT
//

// restkit object manager
NSString *baseURL = @"http://test1.website.com";
RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:baseURL]];

// enable activity indicator
[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

// managed object model
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"AppName" withExtension:@"momd"];
NSManagedObjectModel *managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
// NSLog(@"managed object model: %@", managedObjectModel);

// managed object store
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];
objectManager.managedObjectStore = managedObjectStore;
// NSLog(@"managed object store: %@", managedObjectStore);

// persistent store
NSError *error;
NSString *storePath = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"AppName.sqlite"];
NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:storePath fromSeedDatabaseAtPath:nil withConfiguration:nil options:nil error:&error];
if (error) {
    NSLog(@"unresolved error %@, %@", error, [error userInfo]);
    abort();
}
// NSLog(@"persistent store coordinator: %@", managedObjectStore.persistentStoreCoordinator);
// NSLog(@"persistent store: %@", persistentStore);

// managed object contexts
[managedObjectStore createManagedObjectContexts];
// NSLog(@"managed object context: %@", managedObjectStore.mainQueueManagedObjectContext);

// managed object cache
managedObjectStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:managedObjectStore.mainQueueManagedObjectContext];
// NSLog(@"mangaged object cache: %@", managedObjectStore.managedObjectCache);

//
// entity mapping
//

// album entity mapping
RKEntityMapping *albumEntityMapping = [RKEntityMapping mappingForEntityForName:@"Album" inManagedObjectStore:managedObjectStore];
albumEntityMapping.identificationAttributes = @[ @"identifier" ];
[albumEntityMapping addAttributeMappingsFromDictionary:@{ @"title" : @"title" }];

//
// response descriptor
//

// album response descriptor
[objectManager addResponseDescriptor:[RKResponseDescriptor responseDescriptorWithMapping:albumEntityMapping pathPattern:[NSString stringWithFormat:@"/albums/display/%@/%@", userInfo[@"userID"], userInfo[@"apiKey"]] keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]];

I'm requesting the information from the API via a UITableViewController class:

- (void)loadObjectsFromResourcePath:(NSString *)resourcePath;
{
   [[RKObjectManager sharedManager] getObjectsAtPath:resourcePath parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
        NSLog(@"mapping result: %@", [mappingResult array]);
        [self stopLoading];
    } failure:^(RKObjectRequestOperation *operation, NSError *error) {
        NSLog(@"error: %@", error);
        [self stopLoading];
    }];
}

However, with this code I get the following errors:

2012-12-05 17:08:14.830 AppName Alpha[1310:907] I restkit:RKLog.m:34 RestKit logging initialized...
2012-12-05 17:08:15.107 AppName Alpha[1310:907] resource path: albums/display/102/drrrbSAt6RFLsgHaKiiB6kBIyYRyzxLYinL84Kba
2012-12-05 17:08:15.113 AppName Alpha[1310:907] I restkit.support:RKMIMETypeSerialization.m:115 JSON Serialization class 'RKNSJSONSerialization' detected: Registering for MIME Type 'application/json
2012-12-05 17:08:15.118 AppName Alpha[1310:1603] I restkit.network:RKHTTPRequestOperation.m:141 GET 'http://test1.AppName.com/albums/display/102/drrrbSAt6RFLsgHaKiiB6kBIyYRyzxLYinL84Kba'
2012-12-05 17:08:15.122 AppName Alpha[1310:907] error (null), (null)
2012-12-05 17:08:35.333 AppName Alpha[1310:3e13] I restkit.network:RKHTTPRequestOperation.m:158 GET 'http://test1.AppName.com/albums/display/102/drrrbSAt6RFLsgHaKiiB6kBIyYRyzxLYinL84Kba' (200)
2012-12-05 17:08:35.351 AppName Alpha[1310:1507] CoreData: error: Failed to call designated initializer on NSManagedObject class 'AppName Album' 
2012-12-05 17:08:35.355 AppName Alpha[1310:1507] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<AppName 0x1c579380> valueForUndefinedKey:]: the entity (null) is not key value coding-compliant for the key "Title".'
*** First throw call stack:
(0x39e503e7 0x38ea9963 0x39e500d5 0x371f8d81 0x3276cc1d 0xbf545 0xc00f5 0xc0ab9 0xc44c5 0x32791299 0xb738b 0xb6e5f 0xb7ca5 0xb8343 0xb895b 0x32791299 0xf96ef 0xf8c4b 0x32791299 0x328097f7 0x32c38793 0x32c3c657 0x32c3c7d9 0x3312a7f1 0x3312a684)
libc++abi.dylib: terminate called throwing an exception

You can take a peak at the returned JSON object here: http://test1.AppName.com/albums/display/102/drrrbSAt6RFLsgHaKiiB6kBIyYRyzxLYinL84Kba


Source: (StackOverflow)

Rails shows "WARNING: Can't verify CSRF token authenticity" from a RestKit POST

When I try to POST from RestKit, there is a warning in Rails console:

Started POST "/friends" for 127.0.0.1 at 2012-04-16 09:58:10 +0800
Processing by FriendsController#create as */*
Parameters: {"friend"=>{"myself_id"=>"m001", "friend_id"=>"f001"}}
WARNING: Can't verify CSRF token authenticity
(0.1ms)  BEGIN
SQL (1.7ms)  INSERT INTO `friends` (`friend_id`, `myself_id`) VALUES ('f001', 'm001')
(1.1ms)  COMMIT
Redirected to http://127.0.0.1:3000/friends/8
Completed 302 Found in 6ms (ActiveRecord: 3.0ms)

Here is client code:

NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
[attributes setObject: @"f001" forKey: @"friend_id"];
[attributes setObject: @"m001" forKey: @"myself_id"];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:attributes forKey:@"friend"];
[[RKClient sharedClient] post:@"/friends" params:params delegate:self];

How can I get rid of the warning?


Source: (StackOverflow)

Advertisements

Using the force_load linker flag with RestKit (iOS)

I am using the Facebook iOS SDK, the AWS iOS SDK, and RestKit. To make Facebook and AWS play nice (there were duplicate symbols), I had to change my other linker flags to -force_load facebook-ios-sdk/lib/facebook-ios-sdk/libfacebook_ios_sdk.a. Now, I am getting this RestKit-related error when I run my app:

2012-06-28 15:55:15.336 MyApp[1640:707] -[__NSCFString isIPAddress]: unrecognized selector sent to instance 0x35f440

2012-06-28 15:55:15.338 MyApp[1640:707] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString isIPAddress]: unrecognized selector sent to instance 0x35f440'

I cannot use the -ObjC and all-load linker flags because that prevents me from building with Facebook and AWS.

Does anyone know how I should set my linker flags so that I can use all 3 (FB, AWS, RestKit) together? Thanks!


Source: (StackOverflow)

RestKit: distinguish multiple requests in didLoadResponse:

I'd like to use RestKit and handle several different requests in the same class, i.e. in the didLoadResponse: method. How can I distinguish between the different requests? How do I know which request is finished?

I'm doing the request via

RKClient *client = [RKClient sharedClient];
[client get:@"/....", method] delegate:self];

Then, in the delegate-method

- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response {
    if (???) // request which gets XY returned
        ...
    else if (???) // request which gets YZ returned
        ...
}

is that possible?


Source: (StackOverflow)

RestKit Performance and Core Data

RestKit performance is unacceptably slow when downloading just shy of 9,000 objects — it's taking 10 minutes on the simulator, and indefinite time on an iPad Mini.

I have several tables I'm downloading from a restful interface. It all works, but there appears to be an exponential scale problem that becomes intolerable when there are many objects. The following table has the most problems:

optionMapping.identificationAttributes = @[@"optionID"];

// OptionType
RKEntityMapping *optionTypeMapping = [RKEntityMapping mappingForEntityForName:@"OptionType" inManagedObjectStore:rkMOS];
[optionTypeMapping addAttributeMappingsFromDictionary:@{
 @"id" : @"optionTypeID",
 @"option_type" : @"optionType",}];

optionTypeMapping.identificationAttributes = @[@"optionTypeID"];

The attribute optionTypeID is indexed in Core Data, and is not optional.

There are some relationships to other tables, which I map as follows:

// Option.optionType -> OptionType

[optionMapping addConnectionForRelationship:@"optionType" connectedBy: @"optionTypeID"];

// Option.unit -> Unit

[optionMapping addConnectionForRelationship:@"unit" connectedBy:@"unitID"];

These don't seem to be the problem -- I commented them out, and the download is still very, very slow.

I set up a response descriptor (this is a catalog, so I only need to download it). Note that the following code shows a setup for all of the tables.

NSArray *reqA = @[@{@"endpoint" : API_VENDORS_ENDPOINT,
                    @"mapping" : vendorMapping},

                  @{@"endpoint" : API_OPTION_TYPES_ENDPOINT,
                    @"mapping" : optionTypeMapping},

                  @{@"endpoint" : API_OPTIONS_ENDPOINT,
                    @"mapping" : optionMapping},

                  @{@"endpoint" : API_UNITS_ENDPOINT,
                    @"mapping" : unitMapping},

                  @{@"endpoint" : API_PRICE_TIERS_ENDPOINT,
                    @"mapping" : priceTierMapping},

                  @{@"endpoint" : API_PRODUCT_TYPES_ENDPOINT,
                    @"mapping" : productTypeMapping},

                  @{@"endpoint" : API_PRODUCTS_ENDPOINT,
                    @"mapping" : productMapping}
                  ];

for (NSDictionary *mapD in reqA) {

    RKResponseDescriptor *thisRD = [RKResponseDescriptor
                                    responseDescriptorWithMapping:[mapD valueForKey:@"mapping"]
                                    pathPattern:[mapD valueForKey:@"endpoint"]
                                    keyPath:nil
                                    statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];

    [_objMgr addResponseDescriptor:thisRD];

I'm using the object manager to download the table:

[_objMgr getObjectsAtPath:verbStr
              parameters:nil
                 success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                     RKLogInfo(@"%@ load complete: %@", verbStr, [NSDate date]);

                     NSInteger idx = [loadA indexOfObject:verbStr] + 1;

                     if (idx < [loadA count]) {
                         [self load:[loadA objectAtIndex:idx] stack:loadA];
                     }

                     [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:verbStr];
                     [[NSUserDefaults standardUserDefaults] synchronize];

                     NSDictionary *options = @{@"verb" : verbStr};
                     [[NSNotificationCenter defaultCenter] postNotificationName:OBJECTS_DOWNLOADED object:self userInfo:options];

                 } failure:^(RKObjectRequestOperation *operation, NSError *error) {
                     RKLogError(@"Load failed with error: %@", error);

                     NSInteger statusCode = operation.HTTPRequestOperation.response.statusCode;

                     if (401 == statusCode) {
                         [self resetAdmin];
                     }
                 }];

The console output shows that mapping is chugging along, but it takes forever. The following is just one snippet from thousands like it:

2013-08-01 17:11:49.319 CarpetDirect[138:1507] D restkit.object_mapping:RKMappingOperation.m:952 Starting mapping operation...
2013-08-01 17:11:49.321 CarpetDirect[138:1507] T restkit.object_mapping:RKMappingOperation.m:953 Performing mapping operation: <RKMappingOperation 0x1dda2160> for 'Option' object. Mapping values from object {
   id = 1307;
   "option_type" = 0;
   unit = "<null>";
   value = "939 Puddle";
} to object <Option: 0x1dd55020> (entity: Option; id: 0x1dd55060 <x-coredata:///Option/t3ABD9C1C-1BBA-4C39-AEF7-EB3D1D9AFC0B1334> ; data: {
   optionID = 1307;
   optionType = nil;
   optionTypeID = 0;
   orderedItems =     (
);
   products =     (
);
   unit = nil;
   unitID = 0;
   value = nil;
}) with object mapping (null)
2013-08-01 17:11:49.324 CarpetDirect[138:1507] T restkit.object_mapping:RKMappingOperation.m:550 Mapping attribute value keyPath 'id' to 'optionID'
2013-08-01 17:11:49.326 CarpetDirect[138:1507] T restkit.object_mapping:RKMappingOperation.m:583 Skipped mapping of attribute value from keyPath 'id to keyPath 'optionID' -- value is unchanged (1307)
2013-08-01 17:11:49.329 CarpetDirect[138:1507] T restkit.object_mapping:RKMappingOperation.m:550 Mapping attribute value keyPath 'unit' to 'unitID'
2013-08-01 17:11:49.333 CarpetDirect[138:1507] T restkit.object_mapping:RKMappingOperation.m:431 Found transformable value at keyPath 'unit'. Transforming from type 'NSNull' to 'NSNumber'
2013-08-01 17:11:49.334 CarpetDirect[138:1507] T restkit.object_mapping:RKMappingOperation.m:572 Mapped attribute value from keyPath 'unit' to 'unitID'. Value: (null)
2013-08-01 17:11:49.336 CarpetDirect[138:1507] T restkit.object_mapping:RKMappingOperation.m:550 Mapping attribute value keyPath 'value' to 'value'
2013-08-01 17:11:49.338 CarpetDirect[138:1507] T restkit.object_mapping:RKMappingOperation.m:572 Mapped attribute value from keyPath 'value' to 'value'. Value: 939 Puddle
2013-08-01 17:11:49.339 CarpetDirect[138:1507] T restkit.object_mapping:RKMappingOperation.m:550 Mapping attribute value keyPath 'option_type' to 'optionTypeID'
2013-08-01 17:11:49.342 CarpetDirect[138:1507] T restkit.object_mapping:RKMappingOperation.m:583 Skipped mapping of attribute value from keyPath 'option_type to keyPath 'optionTypeID' -- value is unchanged (0)
2013-08-01 17:11:49.345 CarpetDirect[138:1507] D restkit.object_mapping:RKMappingOperation.m:1021 Finished mapping operation successfully...
2013-08-01 17:11:49.348 CarpetDirect[138:1507]

Any ideas on how I can speed this up? All I want to do is blast the data down from the server to Core Data.


Source: (StackOverflow)

RestKit: How does one post an array of objects?

Question summary:

Consider a class SyncObject that is KVC-compliant with properties such as: time, someValue, lastChange, uuid.

Consider an NSArray containing exclusively instances of SyncObject.

I need to submit the array to the server as a JSON array.

How would one submit this array to the server using HTTP POST using RestKit?

Example array:

[
  {
    "time": "14:45 10/21/2011",
    "someValue": "15",
    "lastChange": "14:45 10/21/2011",
    "uuid": "0b07c510-f4c8-11e0-be50-0800200c9a66"
  },
  {
    "time": "14:50 10/21/2011",
    "someValue": "62",
    "lastChange": "14:51 10/21/2011",
    "uuid": "1a6d4480-f4c8-11e0-be50-0800200c9a66"
  }
]

Details

I have an array of objects that I need to the server as JSON. It seems to me that RestKit is the easiest way to do this: I'm trying to avoid converting objects into a set of NSDictionary objects, and then using some JSON encoder to get JSON which I can POST to the server.

So, having created the array, and having set up the mapping for the class of objects stored in the array, I naturally try to POST to the server.

RKObjectManager* mgr = [RKObjectManager objectManagerWithBaseURL:@"http://localhost/someweb/api/"];
mgr.serializationMIMEType = RKMIMETypeFormURLEncoded;
mgr.client.username = @"username";
mgr.client.password = @"password";
RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]];
[mapping mapKeyPath: @"time"       toAttribute:@"time"         ];  
[mapping mapKeyPath: @"someValue"  toAttribute:@"someValue"    ];
[mapping mapKeyPath: @"lastChange" toAttribute:@"lastChange"   ];
[mapping mapKeyPath: @"uuid"       toAttribute:@"uuid"         ];
RKObjectMapping* mappingForSerialization = [mapping inverseMapping];
[mgr.mappingProvider setSerializationMapping:mappingForSerialization 
                                    forClass:[NSManagedObject class]];

[mgr.router routeClass:[NSManagedObject class] toResourcePath:@"/sync" forMethod:RKRequestMethodPOST];    

[mgr postObject:array delegate:nil/*self*/];

However, this is what I get out:

2011-10-11 14:57:51.769 AppConnect[1974:6e0b] *** Terminating app due to uncaught exception '(null)', reason: 'Unable to find a routable path for object of type '__NSArrayI' for HTTP Method 'POST''

Apparently, RestKit does not know how to handle NSArrays.

How does one post an array of objects using RestKit?


I've tried something different: I replaced the last line with a manual send through RKObjectLoader.

//[mgr postObject:[NSMutableDictionary dictionaryWithObject:array forKey:@"data"] delegate:nil/*self*/];


NSString* syncPath = @"/sync"; 
RKObjectLoader * objectLoader = [mgr objectLoaderWithResourcePath:syncPath delegate:self];
objectLoader.serializationMIMEType = RKMIMETypeJSON;
objectLoader.method = RKRequestMethodPOST;
//objectLoader.objectClass = [NSManagedObject class];       
//objectLoader.managedObjectStore = mgr.objectStore; 
objectLoader.params = [NSDictionary dictionaryWithObject:array 
                                                  forKey:@"MyData"]; 
[objectLoader send];

Unfortunately, this does not apply mapping of any sort, and instead transmits an array of objects' descriptions. Setting serializationMIMEType also does not affect the structure of transmitted contents, and params are always transmitted as application/x-www-form-urlencoded.

I also tried assigning serialization mapping and passing the object as targetObject and sourceObject (this seems to be what RestKit does internally in -[RKObjectManager postObject:delegate:]).

RKObjectLoader * objectLoader = [mgr objectLoaderWithResourcePath:syncPath delegate:self];
objectLoader.method = RKRequestMethodPOST;
//objectLoader.objectClass = [NSManagedObject class];       
//objectLoader.managedObjectStore = mgr.objectStore; 
objectLoader.params = [NSMutableDictionary dictionaryWithObject:array 
                                                  forKey:@"MyData"]; 
objectLoader.serializationMapping = mapping;
objectLoader.serializationMIMEType = RKMIMETypeJSON;
objectLoader.sourceObject = objectLoader.params;
objectLoader.targetObject = objectLoader.params;
[objectLoader send];

Unfortunately, no mapping occurs this way:

2011-10-12 12:36:48.143 MyProject[5119:207] D restkit.network:RKObjectLoader.m:290 POST or PUT request for source object {
    MyData =     (
        "<NSManagedObject: 0x5935430> (entity: SomeRecord; id: 0x5934da0 <x-coredata://64DF9977-DA50-4FCD-8C20-4132E58439BF/SomeRecord/p1> ; data: <fault>)",
        "<NSManagedObject: 0x5935730> (entity: SomeRecord; id: 0x5934db0 <x-coredata://64DF9977-DA50-4FCD-8C20-4132E58439BF/SomeRecord/p2> ; data: <fault>)"
    );
}, serializing to MIME Type application/json for transport...
2011-10-12 12:36:48.143 MyProject[5119:207] D restkit.object_mapping:RKObjectMappingOperation.m:428 Starting mapping operation...
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'time'
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'someValue'
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'lastChange'
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'uuid'
2011-10-12 12:36:48.145 MyProject[5119:207] D restkit.object_mapping:RKObjectMappingOperation.m:448 Mapping operation did not find any mappable content
2011-10-12 12:36:48.146 MyProject[5119:207] T restkit.network:RKRequest.m:211 Prepared POST URLRequest '<NSMutableURLRequest http://someurl/api/sync?request=provide_key>'. HTTP Headers: {
    Accept = "application/json";
    "Content-Length" = 0;
}. HTTP Body: .

Source: (StackOverflow)

How should I be associating Core Data entities for use with RestKit?

I have two Core Data entities (Client and UserFile) that I have successfully set up a relationship between.

I have created classes for both entities, and made them subclasses of RKManagedObject.

When I create a new UserFile, I want to correctly associate it with a Client. Here's what I'm doing:

Client *client = [Client objectWithPrimaryKeyValue:@"1"];
UserFile *file = [UserFile object];
file.client = client;
file.clientId = client.clientId;
[[RKObjectManager sharedManager] postObject:file delegate:self];

It seems like I have to assign file.clientId so that the correct parameter is sent to the server (if I only assign file.client then the submitted client_id is blank).

It seems like I have to assign file.client to prevent a new, empty Client from being created and associated with the file (the client relationship is required).

Is this correct? Do I really have to assign both the foreign key and the actual entity? This seems a bit redundant to me, but I'll happily admit that my Core Data and RestKit knowledge is lacking!


Source: (StackOverflow)

json response is interpreted as text/plain

I have the following code:

NSURL *URL = [NSURL URLWithString:[@"some-address"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];

RKObjectRequestOperation *requestOperation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:[self.objectManager responseDescriptors]];

[requestOperation start];
[requestOperation waitUntilFinished];

I get the following error.

Object request failed: Underlying HTTP request operation failed with error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected content type {(
    "application/x-www-form-urlencoded",
    "application/json"
)}, got text/plain" UserInfo=0x1f5e3c40 {NSLocalizedRecoverySuggestion={"total_rows":16,"offset":1,"rows":[

{"id":"1","key":1,"value":{"_id":"1","_rev":"1-e75042683867a7030fc4d3aa3b72ef35",
"user":{
"userId":"1",
"name":"A",
.......
]}}, .....

Why I get this error, when the response is in Json format?


Source: (StackOverflow)

RestKit Object Mapping relationships with foreign keys

Can RestKit connect a relationship without storing the foreign key as an attribute, i.e., directly from the keypath in the JSON?

In particular, I've got a Job has_many Rooms relationship. The room's JSON doesn't contain the job, rather, both are loaded separately:

- job: {
    id: 1,
    name: "John"
}

- room: {
    id: 4,
    job_id: 1,
    name: "spare bedroom"
}

The Job is loaded before the Room.

My CoreData models, Job has properties for

@interface Job : NSManagedObject
@property (nonatomic, retain) NSNumber * identifier;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSSet *rooms;
@end

@interface Room : NSManagedObject
@property (nonatomic, retain) NSNumber * identifier;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) Job *job;
@end

Currently I add a @property (nonatomic, strong) NSNumber *jobID; to Room, which I @synthesize.

JobMapping:
    mapping = [RKManagedObjectMapping mappingForClass:[Job class]];
    [mapping setPrimaryKeyAttribute:@"identifier"];

    [mapping mapAttributes:@"name", nil];
    [mapping mapKeyPath:@"id" toAttribute:@"identifier"];

    [mapping mapRelationship:@"rooms" withMapping:[Room objectMapping]];



RoomMapping
    mapping = [RKManagedObjectMapping mappingForClass:[Room class]];
    [mapping setPrimaryKeyAttribute:@"identifier"];

    [mapping mapAttributes:@"name", nil];
    [mapping mapKeyPath:@"id" toAttribute:@"identifier"];
    [mapping mapKeyPath:@"job_id" toAttribute:@"jobID"];

    [mapping mapRelationship:@"job" withMapping:[Job objectMapping]];

    [mapping connectRelationship:@"job" withObjectForPrimaryKeyAttribute:@"jobID"];

I was wondering if there's a way I can do this without the extra jobID property? I don't want to have a jobID attribute in the CoreData xcdatamodeld - it's redundant, as the relationship covers that.

Also if I rebuild the NSManagedObjects, I need to re-add the jobID property, which is tedious. Can't I tell restkit to connect the Room to its corresponding Job via the job_id keypath in the JSON?

If I remove the property, the mapKeyPath:@"job_id" line, and change the last line to [mapping connectRelationship:@"job" withObjectForPrimaryKeyAttribute:@"job_id"]; I get

the entity Room is not key value coding-compliant for the key "job_id".

Source: (StackOverflow)

More than one RKObjectManager at a time (RestKit)

I am testing out RestKit and need to access different BaseUrls and also sometimes access a web service with the same baseUrl from different places "at once", lastly I also need to access the same baseUrl with different ressourcePaths in the same controller.

In my app delegate I set up the RKObjectManager singleton like this.

RKObjectManager *objectManager = [RKObjectManager objectManagerWithBaseURL:kBaseUrl];
[objectManager registerClass:[EntityClass1 class] forElementNamed:@"element1"];
[objectManager registerClass:[EntityClass2 class] forElementNamed:@"element2"];
.
.
.
etc.

The singleton approach is really easy to work with, I however can't figure out how to separate the different web service calls.

In MyViewController, which implement the RKObjectLoaderDelegate, I will have the two methods:

- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects         {
    //stuff with result
}

- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error {
    //stuff with error    
}

This causes no problems when MyViewController uses one RKObjectManager singleton to access one ressourcePath with one baseUrl.

If I start different requests in this way:

[[RKObjectManager sharedManager] loadObjectsAtResourcePath:FLICKRPath delegate:self]
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:FOURSQUAREPath delegate:self]

and so on, within the same MyController, my problem is that FLICKRPath and FOURSQUAREPath of course has different baseUrl, but the RKObjectManager only has one?

If I get this working and can have different RKObjectManagers another problem arises. The delegate methods didLoadObjects and didFailWithError will receive results from both RKObjectManagers and I can't see any other way to tell them apart than from their baseUrls. Potentially comparing each return value with a baseUrl and, even worse, a ressourcePath, in the delegate method does not appeal to me at all.

If I have different RKObjectManagers I guess I could pass them different delegates and build classes dedicated to deal with the return values from different baseUrls and ressourcePaths. This would mean I had to build yet another abstraction on top of MyController and RestKit, which also seems messy.

I have a strong feeling I am going about this in the wrong way, the RestKit source is very impressive which indicates that is me fighting the framework. I would really appreciate some best practice insights on the subject. I have been through all the resources and examples that I could find but have not seen the above use case. It is always one RKObjectManager, one baseUrl and one ressourcePath.

Thank you in advance.


Source: (StackOverflow)

RestKit: Getting HTTP status code when a request fails

I'm using RestKit in an iOS app and I need to have special handling for certain HTTP error codes. How can the the response HTTP status code be checked inside of request:didFailLoadWithError:? Is there some entry in the userInfo dictionary of the NSError?

I couldn't find anything in the RKRequestDelegate documentation.

Here's the interface for the delegate method:

- (void)request:(RKRequest *)request didFailLoadWithError:(NSError *)error

Source: (StackOverflow)

RestKit ios - put - json instead of form encoded

i am writing an ios app that uses restkit to communicate with a web server through Rest with JSON

i am able to use [[RKObjectManager sharedManager] loadObjectsAtResourcePath:path delegate:self] to get object from my web service as JSON, map it to obj-c object, it works fine

now i am trying to use: [[RKObjectManager sharedManager] putObject:obj delegate:self]; and this call sends an object to the web service as form encoded and not JSON

so my question is: how to configure the sharedManager (or the routeur?) to send with content type JSON instead of form encoded.

any code example much appreciated.

Thx!


Source: (StackOverflow)

I can't use my core data model in two targets in a Swift project

The class name for entity models in the Core Data model has to have the app name prepended to it. So for an entity named User the class name in the model editor has to be MyAppName.User. This works fine until I added a second target to my project.

The new project expects the entity class names to be SecondAppTargetName.User. How do we support two targets using the same core data model? I tried prepending ${PRODUCT_NAME}.User instead, not expecting it to work. And it doesn't work.

Any ideas on how to share one core data model between targets and satisfy the need of Swift projects to have the PRODUCT_NAME prepended to the class in the model editor?

EDIT: It appears from the Apple documentation here that adding the module name as a prefix to the class name in the model entity inspector is the preferred behavior. If so this seems like a gaping hole since it precludes multiple targets using the same data model. I still have found no workaround for this yet. Some posts here on SO have indicated that using @objc(ClassName) in front of the Swift class definition for the managed object will do the trick, but I haven't been able to verify that yet.


Source: (StackOverflow)

Restkit json error response msg from server

I have used many hours on how to solve this issue. Im using Restkit 0.9.3 with Object Mapping 2.0. All data is in JSON. I can make GET, POST, PUT and DELETE operations correctly, it's the response body I dont catch and map corretly..

So my problem is that my restful api is returning errors when something goes wrong. I want to map those errors with restkit, fx this error is returned:

{ "code": "401", "message": "Unauthorized" }

How do I map this json correct? I have tried lots of things and could use some guideness - or please give an example of this.


Source: (StackOverflow)

Rails and iOS app, authentication question

I want to build web service in Rails 3 and iOS app to work with this service. I need simple thing. User when first time open iOS app, get login screen. When is logged in, iOS app can send and get requests.

I already used Devise for authentication on Rails, and found RESTKit for iOS to map objects and use RESTfull web services, bit I didn't found anything about to confirm to work together.

My question is, what is the best solution to use on both sides, iOS and RoR to make this to work?


Source: (StackOverflow)