2012-02-20 102 views
0

在我的第一视图控制器(MonitorViewController),这是在接口文件MonitorViewController.h:在IOS 5消耗RESTful Web服务

#import <RestKit/RestKit.h> 
@interface MonitorViewController : UIViewController <RKRequestDelegate> 

在MonitorViewController.m viewDidLoad方法,我这个底:

RKClient* client = [RKClient clientWithBaseURL:@"http://192.168.2.3:8000/DataRecorder/ExternalControl"]; 
NSLog(@"I am your RKClient singleton : %@", [RKClient sharedClient]); 
[client get:@"/json/get_Signals" delegate:self]; 

的委托方法MonitorViewController.m实施:

- (void) request: (RKRequest *) request didLoadResponse: (RKResponse *) response { 
    if ([request isGET]) {   
     NSLog (@"Retrieved : %@", [response bodyAsString]); 
    } 
} 

- (void) request:(RKRequest *)request didFailLoadWithError:(NSError *)error 
{ 
    NSLog (@"Retrieved an error"); 
} 

- (void) requestDidTimeout:(RKRequest *)request 
{ 
    NSLog(@"Did receive timeout"); 
} 

- (void) request:(RKRequest *)request didReceivedData:(NSInteger)bytesReceived totalBytesReceived:(NSInteger)totalBytesReceived totalBytesExectedToReceive:(NSInteger)totalBytesExpectedToReceive 
{ 
    NSLog(@"Did receive data"); 
} 

我的AppDelegate方法DidFinishLaunchingWithOptions方法只返回YES而没有其他东西。

回答

0

我推荐使用RestKit framework。随着restkit,你只需要做:

// create the parameters dictionary for the params that you want to send with the request 
NSDictionary* paramsDictionary = [NSDictionary dictionaryWithObjectsAndKeys: @"00003",@"SignalId", nil]; 
// send your request 
RKRequest* req = [client post:@"your/resource/path" params:paramsDictionary delegate:self]; 
// set the userData property, it can be any object 
[req setUserData:@"SignalId = 00003"]; 

,然后在委托方法:

- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response { 
    // check which request is responsible for the response 
    // to achieve this, you can do two things 
    // check the parameters of the request like this 
    NSLog(@"%@", [request URL]); // this will print your request url with the parameters 
    // something like http://myamazingrestservice.org/resource/path?SignalId=00003 
    // the second option will work if your request is not a GET request 
    NSLog(@"%@", request.params); // this will print paramsDictionary 
    // or you can get it from userData if you decide to go this way 
    NSString* myData = [request userData]; 
    NSLog(@"%@", myData); // this will log "SignalId = 00003" in the debugger console 
} 

所以你永远不会需要发送未在服务器端使用的参数,只是为了区分你的要求。此外,RKRequest类还有许多其他属性,您可以使用它们来检查哪个请求对应于给定的响应。但是如果你发送了一堆相同的请求,我认为userData是最好的解决方案。

RestKit还将帮助您处理其他常见的休息界面任务。

+0

它会帮助我区分哪个响应对应于哪个请求,如果我发送10请求是这样的: http://mywebservice.com/myservice?dev=1 http://mywebservice.com/myservice?dev=2 ... http://mywebservice.com/myservice?dev= 10 – Torben 2012-02-20 14:02:13

+0

是的,但如果您的Web服务没有真正使用* dev *参数,我不推荐使用它。看到我更新的答案。 – lawicko 2012-02-20 15:00:01

+0

也许我没有解释得很清楚。我会再试一次:-) – Torben 2012-02-22 12:49:56