如何使用RestKit 0.20将简单对象的数据发布到服务器

时间:2014-04-09 18:01:04

标签: objective-c restkit-0.20

我是RestKit的新手。我没有找到将简单对象数据发送到Restful API的正确文档或教程。

这是我的问题。

我有一个名为用户的课程,现在有两个属性:电子邮件和密码。 我想使用RestKit 0.20将它们发送到服务器。

我找到了一些教程,但所有这些教程都因RestKit v 0.10而过时。我找到了this question,但这也已经过时了。 RestKit 0.20中没有类 RKObjectManager sharedInstance 选择器,但 sharedManager

任何帮助都会很棒。

1 个答案:

答案 0 :(得分:1)

最后我找到了解决方案。谢谢@Mateusz帮助我。 这是解决方案。

// Construct a request mapping for User
RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];
[requestMapping addAttributeMappingsFromDictionary:@{ @"email": @"email", @"password": @"password" }];


// construct a response mapping for User
RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[User class]];
[responseMapping addAttributeMappingsFromDictionary:@{@"email": @"email", @"password": @"password", @"guid": @"guid"}];


RKRequestDescriptor *req = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping objectClass:[User class] rootKeyPath:@"user" method:RKRequestMethodPOST];

RKResponseDescriptor *res = [RKResponseDescriptor responseDescriptorWithMapping:responseMapping method:RKRequestMethodAny pathPattern:nil keyPath:@"user" statusCodes:[NSIndexSet indexSetWithIndex:200]];

// Register our descriptors with a manager
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://localhost/api/user/"]];

[manager addRequestDescriptor:req];
[manager addResponseDescriptor:res];

// preparing sending User object
User *user = [User new];
user.email = @"example@example.com";
user.password = @"password";

NSLog(@"user email : %@", user.email);

[manager postObject:user path:@"user" parameters:@{@"api_key": MY_API_KEY} success:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
    NSArray *arr = [result array];
    User *temp= [arr objectAtIndex:0];
    NSLog(@"SUCCESS ---------------------------- User's email: %@", temp.email);
    NSLog(@"User's guid: %@", temp.guid);

    //                                NSLog(@"--------- - --- -- - all resutl: %@", result);
}
            failure:^(RKObjectRequestOperation *operation, NSError *error) {
                NSLog(@"failed post %@", error);
                NSLog(@"%@",operation.description);
                NSLog(@"%@",operation.HTTPRequestOperation.description);
            }];