RestKit 是一套專為 iOS 與 OS X 打造的 Objective-C 框架,目標是讓「串接 RESTful 服務」這件事變得簡單又快速。它以強大的物件映射系統為核心,搭配乾淨的 HTTP 請求/回應 API,能大幅減少樣板程式碼。
RestKit is a framework for consuming and modeling RESTful web resources on iOS and OS X.
1. 高階的 HTTP 請求/回應層:RestKit 在 NSURLConnection 之上建立了 HTTP 客戶端,並提供判斷 MIME 類型與狀態碼的工具函式。送出表單很簡單,也能靠一個本地參數物件輕鬆產生 multipart 提交。
2. 可快速切換伺服器環境:RestKit 使用 base URL 加資源路徑,而不是寫死完整網址,因此可以迅速在開發機、測試機與正式環境之間切換,不必再手動組字串。
3. Core Data 整合:以物件映射層為基礎,RestKit 能將遠端資源直接映射成本地 Core Data 物件,並提供友善的 API 簡化設定與查詢。
4. 物件映射系統:把回傳的資料結構宣告式地映射成 Cocoa 物件,開發者只要送出請求、異步取得結果,不必自己寫解析。映射底層採用鍵值編碼(KVC),並利用 runtime 的屬性型別資訊,把日期字串自動轉成 NSDate。
5. 可預先產生資料庫:使用 Core Data 儲存時,可以事先從固定資料集產生 sqlite 檔一起打包進 App,使用者第一次啟動就有資料可用。
6. 可替換的解析層:目前透過 SBJSON 與 YAJL 支援 JSON,解析實作在單一介面之後,要換資料格式並不困難。
# -*- coding: utf-8 -*-
#!/usr/bin/env python
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def index():
return 'index'
# 使用 <user> 傳遞參數
@app.route('/hello/<user>')
def hello_get(user):
return 'hello get %s' % user
@app.route('/hello/<user>', methods=['POST'])
def hello_post(user):
return 'hello post %s' % user
@app.route('/json')
def hotCity():
return jsonify({
'article': {
'title': 'My Article',
'author': 'Blake',
'body': 'Very cool!!'
}
})
if __name__ == '__main__':
app.run()
啟動後拜訪 https://127.0.0.1:5000/json 就能看到 article 的 JSON 資料。
新增 Article 類別,對應 JSON 中的欄位:
#import <Foundation/Foundation.h>
@interface Article : NSObject
@property (nonatomic) NSString *title;
@property (nonatomic) NSString *author;
@property (nonatomic) NSString *body;
@end
- (void)loadArticles {
NSURL *baseURL = [NSURL URLWithString:@"https://127.0.0.1:5000"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
// 1. 初始化 RestKit
RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:httpClient];
// 2. 建立 mapping,描述 JSON 與 Model 的對應
RKObjectMapping *articleMapping = [RKObjectMapping mappingForClass:[Article class]];
// 3. 指定欄位對應,有多種寫法
[articleMapping addAttributeMappingsFromDictionary:@{
@"title": @"title",
@"author": @"author",
@"body": @"body"
}];
// 4. 註冊 response descriptor
// pathPattern 是 API 路徑,keyPath 是物件在 JSON 中的位置
RKResponseDescriptor *responseDescriptor =
[RKResponseDescriptor responseDescriptorWithMapping:articleMapping
method:RKRequestMethodGET
pathPattern:@"/json"
keyPath:@"article"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptor:responseDescriptor];
// 5. 送出查詢
[[RKObjectManager sharedManager] getObjectsAtPath:@"/json"
parameters:nil
success:^(RKObjectRequestOperation *operation,
RKMappingResult *mappingResult) {
_articles = mappingResult.array;
NSLog(@"count : %ld", (unsigned long)_articles.count);
Article *article = [mappingResult firstObject];
NSLog(@"%@ - %@ - %@", article.title, article.author, article.body);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(@"Failed to get articles...");
}];
}

RestKit 的學習曲線主要在於 mapping 與 descriptor 這幾層概念,一旦理解「路徑比對 → 欄位映射 → 物件輸出」這條流程,後續串任何 API 都是同一套模式。
不過也要提醒,RestKit 已多年未積極維護,新專案若要在 Swift 或近期 Xcode 上使用,會遇到不少相容性問題。目前更主流的選擇是 Alamofire 搭配 Codable 或 ObjectMapper;RestKit 適合作為理解「物件映射式網路層」設計思路的教材。更多用法可參考其 GitHub 首頁。