2012-02-20 2 views
0

В моем первом ViewController (MonitorViewController) это в файле интерфейса MonitorViewController.h:потребляющих успокоительной веб-сервиса в прошивкой 5

#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 возвращает только ДА и ничего больше.

ответ

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

+0

Да, но я не рекомендую его, если ваш веб-сервис действительно не использует параметр * dev *. См. Мой обновленный ответ. – lawicko

+0

Возможно, я недостаточно объяснил себя. Я попробую еще раз :-) – Torben

Смежные вопросы