RestKit 入门

本篇主要简单介绍了一下restkit中的网络连接,字段映射,与RKTableController。并且在最后给出一个简单的load more的RKTableController的派生子类。

RestKit连接:https://github.com/RestKit/RestKit/

一.网络连接

这里主要用到的是RKClient

初始化

复制代码
- (void)initRKClient {

// Initialize with a Base URL 
RKClient* client = [RKClient clientWithBaseURL:@"http://restkit.org"]; ! 
// Setup HTTP AUTH 设置http验证 
client.username = @"restkit"; 
client.password = @"rocks"; ! 
// Set an app-wide API key HTTP header 设置全局的http头
[client setValue:@"123456" forHTTPHeaderField:@"X-RESTKIT-API-KEY"]; ! 
// The first initialized RKClient becomes 
// the sharedClient instance 检测网络
[[RKClient sharedClient] isNetworkAvailable]; 
} 
复制代码

baseURL的作用是一个网络请求的域(host),这样就不用频繁的写全整个url,之后的调用只要附上后面的地址就行了,往下看。

复制代码
- (void)sendRequest {
// Send an HTTP GET request to 'http://restkit.org/contacts' 发送一个get请求,完整的请求路径是“http://restkit.org/contacts
[[RKClient sharedClient] get:@"/contacts" delegate:self]; 
} 
// RKRequestDelegate methods代理方法
- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response {// 成功
RKLogInfo(@"Yay! We Got a response"); 
}
- (void)request:(RKRequest*)request didFailLoadWithError:(NSError *)error { // 失败
RKLogInfo(@"Oh no! We encountered an error: %@", [error localizedDescription]);
}
复制代码

其中[RKClient sharedClient]得到的你第一个生成的RKClient对象。你当然可以不用[RKClient sharedClient],而用你自己另外生成的RKClient对象来访问网络,这样你就可以在一个页面同时发起多个请求了。

更多的发送post请求参考官方文档。

 

二.字段映射

这里主要用到的类是RKObjectManagerRKObjectMapping

用法:比如说你有一个文章列表需要加载,网络发给你的json是

复制代码
{"article_list":[

{"title":"article1","title_id":3},{"title":"article2","title_id":4}]}
复制代码

而你想映射到本地是一个这样的类结构

复制代码
Article{

NSString* aTitle;

int tid;

}
复制代码

那么首先定义类

复制代码
@interface Article

@property(nonatomic,copy)NSString* aTitle;

@property(nonatomic)int tid;

@end

@implement

@synthesize aTitle;

@synthesize tid;

@end
复制代码

然后生成一个映射规则 RKObjectMapping 对象

复制代码
RKObjectMapping *contactMapping = [RKObjectMapping mappingForClass:[Articleclass]];

[contactMapping mapKeyPath:@"title" toAttribute:@"aTitle"];   [contactMapping mapKeyPath:@"title_id" toAttribute:@"tid"];
复制代码

然后生成一个RKobjectManager对象,实现数据获取后直接映射成所需类对象

复制代码
RKObjectManager *manager = [RKObjectManager objectManagerWithBaseURL:@"http:// restkit.org"];

// Ask for & generate JSON json格式数据

manager.acceptMIMEType = RKMIMETypeJSON;

manager.serializationMIMEType = RKMIMETypeJSON;

[[RKObjectManager sharedManager].mappingProvider setMapping:contactMapping

forKeyPath:@"article_list"];
复制代码

其中baseURL和RKClient中的意义相同,[RKObjectManager sharedManager]也是你第一个生成的RKObjectManager对象。注意最后一句,他为JSON的 @"article_list"这个path绑定了contactMapping这种映射关系。如果你的json不是字典结构,而直接就是数组,那么这里设置path为@“”就可以了。

如果你有多个不同的请求,但是数据都是放在“article_list”这个path下面,那么就不能都是用[RKObjectManager sharedManager],而要为其他的请求另外生成RKObjectManager对象,并且要注意retain,否则可能导致解析失败。

最后通过这个RKObjectManager来访问网络资源就可以了。

复制代码
- (void)loadRemoteObjects {

// GET /contacts 完整路径是“http:// restkit.org/contacts”
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/contacts" delegate:self]; 

}

- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects {

if ([objectLoader wasSentToResourcePath:@"/contacts"]) { 
// Introspect the resource path  完成并解析城Article对象保存在objects中
NSLog(@"Nice! We loaded the following contacts: %@", objects); 
} 
} 
- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error {
// Note that failures here can be at the _application_ level in addition to transport 请求失败
NSLog(@"Rats! Failed to load objects: %@", [error localizedDescription]); 
}
复制代码

RKTableController

最终的最终,我们请求了数据之后还是为了显示。RestKit只要短短几行代码就可以把我们的数据显示在tableview中了,这就靠强大的RKTableController

复制代码
RKTableController  *tableController = [VRKTableController tableControllerWithTableView:self.tableView forViewController:self];
// 代理,有开始网络连接,数据加载完成的相关回调
tableController.delegate = self;
// 一行代码实现下拉刷新
tableController.pullToRefreshEnabled = YES;
// 如果没有额外设置RKTableController的objectManager的话,他默认使用[RKObjectManager sharedManager]
[self.tableController mapObjectsWithClass:[Summary class] toTableCellsWithMapping:
  [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) {
        cellMapping.onSelectCellForObjectAtIndexPath = ^void(UITableViewCell *cell, id object, NSIndexPath *indexPath){
//点击事件
        };
// 行高
        cellMapping.rowHeight = 44;
// 设置cell的具体数据
        cellMapping.onCellWillAppearForObjectAtIndexPath = ^(UITableViewCell* cell, id object,
                                                            NSIndexPath* indexPath) {
            Article* article = (Article*)object;
            cell.textLabel.text = article.title;
        }; }]];
// 开始加载资源
    NSString* resourcePath = [NSString stringWithFormat:@"/content"];
    [self.tableController loadTableFromResourcePath:resourcePath];
复制代码

这些就实现了列表展示了,一切看起来都是那么美好,但是,如何load more呢?我找了半天也没有找到很好的方法,所有就自己派生了一个。附上下载

 
分类: iOS
原文地址:https://www.cnblogs.com/Leo_wl/p/2599060.html