如何使用Restkit来POST JSON和映射响应

时间:2012-02-08 23:46:33

标签: objective-c ios restkit

我第一次使用RestKit,其功能设置看起来很棒。我现在多次阅读该文档,我正在努力寻找一种方法将JSON参数POST到一个feed并映射JSON响应。从stackoverflow上搜索,我发现了一种通过GET发送JSON参数的方法,但我的服务器只接受POST。

这是我到目前为止的代码:

RKObjectMapping *issueMapping = [RKObjectMapping mappingForClass:[CDIssue class]];
[objectMapping mapKeyPath:@"issue_id" toAttribute:@"issueId"];
[objectMapping mapKeyPath:@"title" toAttribute:@"issueTitle"];
[objectMapping mapKeyPath:@"description" toAttribute:@"issueDescription"];
RKObjectManager* manager = [RKObjectManager objectManagerWithBaseURL:@"http://restkit.org"];
RKManagedObjectStore* objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"News.sqlite"];
objectManager.objectStore = objectStore;

NSDictionary params = [NSDictionary dictionaryWithObjectsAndKeys: @"myUsername", @"username", @"myPassword", @"password", nil];
NSURL *someURL = [objectManager.client URLForResourcePath:@"/feed/getIssues.json" queryParams:params];

[manager loadObjectsAtResourcePath:[someURL absoluteString] objectMapping:objectMapping delegate:self]

从另一个stackoverflow线程(http://stackoverflow.com/questions/9102262/do-a-simple-json-post-using-restkit),我知道如何使用以下代码执行简单的POST请求:

RKClient *myClient = [RKClient sharedClient];
NSMutableDictionary *rpcData = [[NSMutableDictionary alloc] init ];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];

//User and password params
[params setObject:password forKey:@"password"];
[params setObject:username forKey:@"email"];

//The server ask me for this format, so I set it here:
[rpcData setObject:@"2.0" forKey:@"jsonrpc"];
[rpcData setObject:@"authenticate" forKey:@"method"];
[rpcData setObject:@"" forKey:@"id"];
[rpcData setObject:params forKey:@"params"];

//Parsing rpcData to JSON! 
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON];
NSError *error = nil;
NSString *json = [parser stringFromObject:rpcData error:&error];    

//If no error we send the post, voila!
if (!error){
    [[myClient post:@"/" params:[RKRequestSerialization serializationWithData:[json dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON] delegate:self] send];
}

我希望有人能帮助我将这两个代码片段结合成一个可行的解决方案。

1 个答案:

答案 0 :(得分:1)

要发布对象我所做的是将路径对象相关联。然后使用 RKObjectManager 中的 postObject 方法。

我认为您已经配置了RestKit,因此您已经设置了基本路径并为您的CDIssue定义了对象映射,就像您已经拥有的代码一样。考虑到这一点,请尝试以下代码:

//We tell RestKit to asociate a path with our CDIssue class
RKObjectRouter *router = [[RKObjectRouter alloc] init];
[router routeClass:[CDIssue class] toResourcePath:@"/path/to/my/cdissue/" forMethod:RKRequestMethodPOST];
[RKObjectManager sharedManager].router = router;

//We get the mapping for the object that you want, in this case CDIssue assuming you already set that in another place
RKObjectMapping *mapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[CDIssue class]];

//Post the object using the ObjectMapping with blocks
[[RKObjectManager sharedManager] postObject:myEntity usingBlock:^(RKObjectLoader *loader) {

    loader.objectMapping = mapping;
    loader.delegate = self;

    loader.onDidLoadObject = ^(id object) {
        NSLog(@"Got the object mapped");
        //Be Happy and do some stuff here
    };

    loader.onDidFailWithError = ^(NSError * error){
        NSLog(@"Error on request");
    };

    loader.onDidFailLoadWithError = ^(NSError * error){
        NSLog(@"Error on load");
    };

    loader.onDidLoadResponse = ^(RKResponse *response) {
        NSLog(@"Response did arrive");
        if([response statusCode]>299){
            //This is useful when you get an error. You can check what did the server returned
            id parsedResponse = [KFHelper JSONObjectWithData:[response body]];
            NSLog(@"%@",parsedResponse);
        }

    };


}];