这里mark下,忙完手里的测试以后写上restful的示例。下面直接说ios下如何使用。
这篇文章写的比较精简。目前只写了get方法。post delete,put 部分下次在补上。
准备工作
首先需要知道restful走的是json协议的数据。为了测试,需要利用服务器返回一段json。大家可以选用熟悉的方法返回。
这里说一个比较简单的学习测试方法。
mac下面开启webshare功能。也就是网络共享。
(10.9以后需要下载http://clickontyler.com/web-sharing/)
对于老的版本。在系统偏好设置->共享下面应该会有设置。
打开launchpad 输入ter 打开命令行。
输入命令
cd /Library/WebServer/Documents
sudo vim articles.json
按住快捷键i,复制粘贴内容
{ "articles": [
{ "title": "RestKit Object Mapping Intro",
"body": "This article details how to use RestKit object mapping...",
"author": "Blake Watters",
"publication_date": "7/4/2011"
},
{ "title": "RestKit 1.0 Released",
"body": "RestKit 1.0 has been released to much fanfare across the galaxy...",
"author": "Blake Watters",
"publication_date": "9/4/2011"
}]
}
Esc切换到视图以后。输入
:wq
同理在articles2.json文件内写入
{ "articles": [
{ "title": "RestKit Object Mapping Intro",
"body": "This article details how to use RestKit object mapping...",
"author": {
"name": "Blake Watters",
"email": "blake@restkit.org"
},
"publication_date": "7/4/2011"
}]
}
在命令行下输入
gem install cocoapods
pod setup
等待安装完成
其他内容可以参考学习 http://blog.devtang.com/blog/2012/12/02/use-cocoapod-to-manage-ios-lib-dependency/
建立工程
打开xcode5在桌面新建1个Master-Detail Controller 项目,命名为restkitDemo工程。关闭。
命令行输入
cd ~/Desktop/restkitDemo
vim Podfile
输入
platform :ios, '5.0'
pod 'RestKit', '~> 0.21.0'
pod 'RestKit/Testing', '~> 0.21.0'
pod 'RestKit/Search', '~> 0.21.0'
:wq保存退出以后
执行
pod install
安装restKit包。
安装完成以后输入
open restkitDemo.xcworkspace
打开项目工程。
编写代码
基本的对象映射
新建Article文件。文件中实现1个从NSobject派生的类。
拷贝替换为一下代码
@interface Article : NSObject
@property (nonatomic, copy) NSString* title;
@property (nonatomic, copy) NSString* body;
@property (nonatomic, copy) NSString* author;
@property (nonatomic) NSDate* publicationDate;
@end
切换到MasterViewController.m中。在
#import "DetailViewController.h"
下链接2个头文件。
#import "Article.h"
#import <RestKit/RestKit.h>
修改ViewDidLoad方法代码为
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.refreshControl beginRefreshing];
[self loadArticles];
}
接着添加如下代码
- (void) loadArticles
{
RKObjectMapping* articleMapping = [RKObjectMapping mappingForClass:[Article class]];
[articleMapping addAttributeMappingsFromDictionary:@{
@"title": @"title",
@"body": @"body",
@"author": @"author",
@"publication_date": @"publicationDate"
}];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:articleMapping
method:RKRequestMethodAny
pathPattern:nil
keyPath:@"articles"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/articles"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
RKObjectRequestOperation *objectRequestOperation = [[RKObjectRequestOperation alloc] initWithRequest:request
responseDescriptors:@[responseDescriptor]];
[objectRequestOperation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
RKLogInfo(@"Load collection of Articles: %@", mappingResult.array);
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects removeAllObjects];
[_objects addObjectsFromArray:mappingResult.array];
[self.refreshControl endRefreshing];
[[self tableView] reloadData];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(@"Operation failed with error: %@", error);
}];
[objectRequestOperation start];
}
修改tableView:cellForRowAtIndexPath:方法代码为
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
Article *object = _objects[indexPath.row];
cell.textLabel.text = object.title;
cell.detailTextLabel.text = object.author;
return cell;
}
接下来修改detail中cell的style.
编译运行,没有意外会看到如下效果
对象与之间的关系映射
修改loadArticles方法代码为以下代码
RKObjectMapping *authorMapping = [RKObjectMapping mappingForClass:[Author class]];
[authorMapping addAttributeMappingsFromArray:@[@"name", @"email"]];
RKObjectMapping *articleMapping = [RKObjectMapping mappingForClass:[Article class]];
[articleMapping addAttributeMappingsFromDictionary:@{
@"title": @"title",
@"body": @"body",
@"publication_date": @"publicationDate"
}];
[articleMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"author"
toKeyPath:@"author"
withMapping:authorMapping]];
RKResponseDescriptor * responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:articleMapping
method:RKRequestMethodAny
pathPattern:nil
keyPath:@"articles"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/articles2"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
RKObjectRequestOperation *objectRequestOperation = [[RKObjectRequestOperation alloc] initWithRequest:request
responseDescriptors:@[responseDescriptor]];
[objectRequestOperation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
RKLogInfo(@"Load collection of Articles: %@", mappingResult.array);
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects removeAllObjects];
[_objects addObjectsFromArray:mappingResult.array];
[self.refreshControl endRefreshing];
[[self tableView] reloadData];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(@"Operation failed with error: %@", error);
}];
[objectRequestOperation start];
修改tableView:cellForRowAtIndexPath:方法的代码为:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
Article *object = _objects[indexPath.row];
cell.textLabel.text = object.title;
cell.detailTextLabel.text = object.author.name;
return cell;
}
修改Article.h中代码为
#import <Foundation/Foundation.h>
@interface Author : NSObject
@property (nonatomic, copy) NSString* name;
@property (nonatomic, copy) NSString* email;
@end
@interface Article : NSObject
@property (nonatomic, copy) NSString* title;
@property (nonatomic, copy) NSString* body;
@property (nonatomic) Author* author;
@property (nonatomic) NSDate* publicationDate;
@end
Article.m中代码为
#import "Article.h"
@implementation Author
@end
@implementation Article
@end
自此修改完成。编译运行。你会看到
关键部分
按照restkit的设计思路。
1个完整的过程分为
1:建立数据映射表。
2:建立返回的响应处理方式(增删改查的控制,构造中填写数据映射表)
3:新建1个url请求(注意,这里可以构造比较复杂的查询)
4:建立request操作,提交请求和返回处理方式。在block中处理成功与错误的返回。返回回来的数据会自动处理为对象。
分析下来还是比较好理解的。