2012-02-20 87 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