0

我正在使用 restkit 0.2 对服务器执行发布请求。这是设置代码:

- (void)setupRestKit { //create RestKit object managers, one for API and one fore OAuth due to being seperate endpoings. API Object manager is default. RKObjectManager *apiObjectManager = [self instantiateAPIObjectManager]; _oauthObjectManager = [self instantiateOAuthObjectManager];

//create object store for core data persistence
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:[NSManagedObjectModel mergedModelFromBundles:nil]];

//provide store to object manager
_oauthObjectManager.managedObjectStore = managedObjectStore;
apiObjectManager.managedObjectStore = managedObjectStore;

//add default formatter for timestamp strings
NSTimeZone *UTC = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
[RKObjectMapping addDefaultDateFormatterForString:@"yyyy-MM-dd HH:mm:ss" inTimeZone:UTC];

// Register mappings
[KaptureOAuthToken registerEntityMappingWithObjectManager:self.oauthObjectManager];

[managedObjectStore createPersistentStoreCoordinator];

//create sqlite persistant store to cache data to disk
NSString *path = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"kapture.sqlite"];
NSError *error;
NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:path
                                                                 fromSeedDatabaseAtPath:nil
                                                                      withConfiguration:nil
                                                                                options:@{
                                                                                          NSInferMappingModelAutomaticallyOption: @YES,
                                                                                          NSMigratePersistentStoresAutomaticallyOption: @YES
                                                                                        }
                                                                                  error:&error];
NSAssert(persistentStore, @"Failed to add persistent store with error: %@", error);

//create in-memory cache so objects are not persisted more than once
managedObjectStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:managedObjectStore.persistentStoreManagedObjectContext];

//create contexts for core data objects
[managedObjectStore createManagedObjectContexts];

}

  • (RKObjectManager *)instantiateAPIObjectManager { RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:[Environment sharedInstance].apiBaseURL]];

    //show network activity indicator when loading network resources [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

    //set api key as default http header for requests [objectManager.HTTPClient setDefaultHeader:[Environment sharedInstance].apiKey value:@"Api-Key"];

    //set http header for device type (i.e. iPhone 4) and version of the app NSString *deviceName = [NSString stringWithFormat:@"%@ %@", [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion]]; NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary]; NSString *majorVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"]; [objectManager.HTTPClient setDefaultHeader:@"X-Requested-With" value:[NSString stringWithFormat:@"%@ - %@", deviceName, majorVersion]];

    //set http header for api mime type [objectManager setAcceptHeaderWithMIMEType:[Environment sharedInstance].apiAcceptenceHeader];

    objectManager.HTTPClient.allowsInvalidSSLCertificate = YES;

    return objectManager; }

  • (RKObjectManager *)instantiateOAuthObjectManager { RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:[Environment sharedInstance].apiOAuthBaseURL]];

    //show network activity indicator when loading network resources [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

    objectManager.HTTPClient.allowsInvalidSSLCertificate = YES;

    return objectManager; }

-(void)setupNetworkCaching { NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil]; [NSURLCache setSharedURLCache:URLCache]; }

并且 EntityMappings 是通过 NSManagedObject 子类上的一个类别通过这两种方法配置的

+ (void)registerEntityMappingWithObjectManager:(RKObjectManager *)objectManager { RKResponseDescriptor *responseDescriptor;

responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:[self entityMappingUsingStore:objectManager.managedObjectStore]
                                                                  method:RKRequestMethodPOST
                                                             pathPattern:@"/"
                                                                 keyPath:@""
                                                             statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptor:responseDescriptor];

}

  • (RKEntityMapping *)entityMappingUsingStore:(RKManagedObjectStore *)store { RKEntityMapping *mapping = [RKEntityMapping mappingForEntityForName:NSStringFromClass([KaptureOAuthToken class]) inManagedObjectStore:store];

    NSDictionary *attributesDict = @{@"access_token": @"accessToken", @"token_type": @"tokenType", @"expires": @"expirationDate", @"expires_in": @"expiresIn", @"refresh_token": @"refreshToken"};

    mapping.identificationAttributes = @[@"accessToken"];

    [mapping addAttributeMappingsFromDictionary:attributesDict];

    return mapping; }

我的问题是:当我尝试执行 POST 请求时

[oauthObjectManager postObject:nil path:@"/" parameters:params success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { dispatch_async(dispatch_get_main_queue(), ^(){ completion(YES, nil, mappingResult); }); } failure:^(RKObjectRequestOperation *operation, NSError *error) { dispatch_async(dispatch_get_main_queue(), ^(){ [self notifyLoginError:error forNetwork:network]; }); }];

我从服务器得到了预期的响应,一切似乎都很好,但是我在命令行中收到了这个错误。

2013-08-22 17:29:11.949 Kapture[25335:1007] W restkit.core_data.cache:RKEntityByAttributeCache.m:173 Failed to load entity cache. Failed to execute fetch request: (entity: KaptureOAuthToken; predicate: ((null)); sortDescriptors: ((null)); type: NSDictionaryResultType; includesPendingChanges: NO; propertiesToFetch: (( "(), name accessToken, isOptional 1, isTransient 0, entity KaptureOAuthToken, renamingIdentifier accessToken, validation predicates (\n), warnings (\n), versionHashModifier (null)\n userInfo {\n}, attributeType 700 , attributeValueClassName NSString, defaultValue (null)", "(), name objectID, isOptional 1, isTransient 0, entity (null), renamingIdentifier objectID, validation predicates (\n), warnings (\n), versionHashModifier (null)\n userInfo {\n}" )); )

它似乎无法在缓存中找到实体,但我真的不确定。一如既往地感谢任何信息!

4

0 回答 0