IOS --- use RestKit for simple interaction with RESTful web Servers

Source: Internet
Author: User

IOS --- use RestKit for simple interaction with RESTful web Servers

RestKit is an Objective-C framework designed for iOS. It aims to interact with RESTful web services more easily and quickly. It is based on a powerful object ing System and combines a clean and simple HTTP Request/response API, greatly reducing the amount of code required by developers during development.

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

Main features:
1. Simple high-level HTTP Request/Response System: RestKit establishes an HTTP client based on NSURLConnection and provides an effective response library to detect MIME types and status codes. It also makes it easier to submit form data, and a local parameter object can also easily create multiple submissions.
2. The framework supports switching servers and environments: RestKit uses the basic URL and resource path instead of the complete URL, allowing you to quickly switch to the target server. It makes the interpolation URL string and NSURL object a forward expression.
3. Core Data support: Based on the object ing layer, RestKit provides an integrated framework with Apple's Core Data to extend Remote resource ing to local objects. It also provides an API based on the Core Data primitive to simplify configuration and query cases.
4. Object ing System: RestKit provides a modeling layer to load the data of the ing process to the native Cocoa object declaration method. In this way, programmers do not have to worry about parsing. They only need a simple request framework to asynchronously obtain remote resources and call the delegate results. Object ing is implemented using key-value encoding, allowing you to quickly traverse parsed object graphs. Reflection is used on the property type to map remote date encoding to a string and return it to the NSDate object.
5. Generate database files: when using Core Data object storage, you can generate a database file from the Data file set. In this way, You can submit your applications and database application packages to the App Store and achieve immediate use.
6. pluggable parsing layer: RestKit currently supports JSON through SBJSON and YAJL Resolvers. Resolution is implemented behind a simple interface and allows transparent processing of additional data formats.

A simple example is as follows:

Build an HTTP server

Here, we use Python flask to build a simple http server.

#-*-Coding: UTF-8 -*-#! /Usr/bin/pythonfrom flask import Flask, jsonifyapp = Flask (_ name _) @ app. route ('/') def index (): return 'index' # Use
  
   
Pass the parameter @ app. route ('/hello/
   
    
') Def hello_get (user): return 'Hello get % s' % user # Use POST request @ 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', 'autor': 'bucke', 'body': 'very cool !! '}) If _ name _ =' _ main _ ': app. run ()
    
   
  

In this way, you can obtain the article data by accessing http: // 127.0.0.1: 5000/json.

Create Model

Create an Article class. The header file Article. h is as follows:

#import 
  
   @interface Article : NSObject@property (nonatomic) NSString *title;@property (nonatomic) NSString *author;@property (nonatomic) NSString *body;@end
  
Obtain JSON data

Use RestKit to obtain simple JSON data. The steps are fixed as follows:

-(Void) loadArticles {NSURL * baseURL = [NSURL URLWithString: @ http: // 127.0.0.1: 5000]; AFHTTPClient * httpClient = [[AFHTTPClient alloc] initwitasehburl: baseURL]; // 1. initialize RestKit and interact with RESTful services. RKObjectManager * objectManager = [[RKObjectManager alloc] initWithHTTPClient: httpClient]; // 2. create ings to configure the ing between JSON and local Model. RKObjectMapping * articleMapping = [RKObjectMapping mappingForClass: [Article class]; // 3. you can use multiple methods to parse fields. // [articleMapping addAttributeMappingsFromArray: @ [@ title, @ author, @ body]; [articleMapping progress: @ {@ title: @ title, @ author: @ author, @ body: @ body}]; NSIndexSet * statusCodes = RKStatusCodeIndexSetForClass (signature); // statuscode: 2xx // register mappings with the provider using a response descriptor // pathPattern: API path // keyPath: path of the object in JSON data: RKResponseDescriptor * responseDescriptor = [RKResponseDescriptor descriptor: articleMapping method: descripathpattern: @/json keyPath: @ article statusCodes: [NSIndexSet indexSetWithIndex: 200]; [objectManager addResponseDescriptor: responseDescriptor]; // 4. submit the query NSDictionary * queryParams = nil; [[sharesharedmanager] getObjectsAtPath: @/json parameters: queryParams success: ^ (response * 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...);}];}

Result:

For more instructions, refer to the RestKit github homepage: RestKit.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.