如何在iOS中使用RestKit 2.X



我是使用 RestKit 的新手,但我完全不明白它是如何工作的......拜托,可以在某个地方解释一下吗?

我的 Json 文件是:

    {
    "colors":
    {
        "red":"#f00",
        "green":"#0f0",
        "blue":"#00f",
        "cyan":"#0ff",
        "magenta":"#f0f",
        "yellow":"#ff0",
        "black":"#000"
    }
}

我托管此文件的路径是:http://186.36.181.116/tesis/file.json

我在 ViewDidLoad 方法中尝试的代码是:

    - (void)viewDidLoad
{
    [super viewDidLoad];
    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[colores class]];
    [mapping addAttributeMappingsFromArray:@[@"colors"]];
    NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // Anything in 2xx
    RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodAny pathPattern:@"/tesis/:coloresID" keyPath:@"colors" statusCodes:statusCodes];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://186.36.181.116/tesis/file.json"]];
    RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[responseDescriptor]];
    [operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
        colores *colores = [result firstObject];
        NSLog(@"Mapped the article: %@", colores);
    } failure:^(RKObjectRequestOperation *operation, NSError *error) {
        NSLog(@"Failed with error: %@", [error localizedDescription]);
    }];
    [operation start];
}

我的类"颜色"如下:

#import <Foundation/Foundation.h>
@interface colores : NSObject{}
@property (weak, nonatomic) IBOutlet NSString *colores;
@end

提前非常感谢!!

你可以在这里找到详细的教程和完整的源代码GitHub。

为了正确地将响应映射到 JSON,我们必须执行以下操作:

*为托管对象模型
中的每个实体创建 RKEntityMapping 的实例*添加 JSON 响应键和对象属性
之间的映射*添加嵌入式 JSON 对象和关系
之间的映射*使用映射
创建响应描述符*可选:如果您计划放置或发布,请使用映射创建请求描述符

最新更新