iOS --- 使用RestKit與RESTful web伺服器進行簡單互動

來源:互聯網
上載者:User

iOS --- 使用RestKit與RESTful web伺服器進行簡單互動

RestKit是一款專為iOS設計的Objective-C架構,旨在與RESTful web服務的互動變得更簡單快速。它基於強大的對象映射系統,並且結合了一個乾淨、簡單的HTTP請求/響應API,大大減少了開發人員開發過程中所需的代碼量。

RestKit is a framework for consuming and modeling RESTful web resources on iOS and OS X.

主要特性:
1. 簡單高層次的HTTP請求/響應系統:RestKit在NSURLConnection的基礎上建立了HTTP用戶端,並且提供了一個有效方法庫來檢測MIME類型和狀態代碼。同時讓提交表單資料變得更簡單,且一個本地參數對象還能夠輕鬆地建立多部分提交。
2. 架構支援切換伺服器以及環境:RestKit使用基本的URL和資源路徑,而不是完整的URL,讓你可以快速地切換目標伺服器。讓插值URL字串和構建NSURL對象成為了過去式。
3. Core Data支援:以對象映射層為基礎,RestKit提供了與Apple的Core Data整合架構,用來擴充遠端資源映射到本地的對象。還提供一個很好地基於Core Data原語的API,用來簡化配置和查詢用例。
4. 對象映射系統:RestKit提供了一個建模層,有利於將映射進程資料負載到原生Cocoa對象聲明方式中去。這樣,程式員就不用擔心解析的問題,只需簡單的請求架構,非同步擷取遠端資源以及調用委託結果即可。對象映射使用的是索引值編碼來實現的,允許快速遍曆解析後的對象圖。反射是用在屬性類型上,以便將遠程日期編碼映射為字串返回到NSDate對象。
5. 產生資料庫檔案:當使用Core DataObject Storage Service時,你可以從資料檔案集合中產生一個資料庫檔案。這樣,你就可以將你的應用以及資料庫的應用程式套件組合提交到App Store中,並且可以達到立即使用的效果。
6. 可插入解析層:RestKit目前通過SBJSON和YAJL解析器支援JSON。解析是在一個簡單介面背後實現的,允許額外的資料格式進行透明處理。

簡單的使用執行個體如下:

搭建HTTP server

在這裡使用Python的flask搭建一個簡單的http server.

# -*- coding: utf-8 -*-#!/usr/bin/pythonfrom flask import Flask, jsonifyapp = Flask(__name__)@app.route('/')def index():    return 'index'#使用傳遞參數@app.route('/hello/')def hello_get(user):    return 'hello get %s' % user#使用POST請求@app.route('/hello/', 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()

這樣, 通過訪問http://127.0.0.1:5000/json即可擷取到article的資料.

建立Model

建立Article類, 標頭檔Article.h如下:

#import @interface Article : NSObject@property (nonatomic) NSString *title;@property (nonatomic) NSString *author;@property (nonatomic) NSString *body;@end
擷取JSON資料

通過RestKit擷取簡單的JSON資料, 步驟比較固定, 如下:

- (void)loadArticles {    NSURL *baseURL = [NSURL URLWithString:@http://127.0.0.1:5000];    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];    // 1. 初始化 RestKit, 與RESTful services互動    RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:httpClient];    // 2. 建立 mappings, 用於配置JSON與本地Model的映射資訊    RKObjectMapping *articleMapping = [RKObjectMapping mappingForClass:[Article class]];    // 3. 解析欄位, 有多種方式.    // [articleMapping addAttributeMappingsFromArray:@[@title, @author, @body]];    [articleMapping addAttributeMappingsFromDictionary:@{                                                         @title: @title,                                                         @author: @author,                                                         @body: @body                                                         }];    NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // statuscode: 2xx    // register mappings with the provider using a response descriptor    // pathPattern: API路徑    // keyPath: 對象在JSON資料中的路徑    RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:articleMapping method:RKRequestMethodGET pathPattern:@/json keyPath:@article statusCodes:[NSIndexSet indexSetWithIndex:200]];    [objectManager addResponseDescriptor:responseDescriptor];    // 4. 提交查詢    NSDictionary *queryParams = nil;    [[RKObjectManager sharedManager] getObjectsAtPath:@/json parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {        _articles = mappingResult.array;        NSLog(@_articles.count : %ld, _articles.count);        Article *article = [mappingResult firstObject];        NSLog(@article : %@ - %@ - %@, article.title, article.author, article.body);    } failure:^(RKObjectRequestOperation *operation, NSError *error) {        NSLog(@Failed to get articles...);    }];}

結果:

更多使用方法請參考RestKit的github首頁: RestKit.

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.