использование полноценного веб-сервиса в iOS 5 - PullRequest
0 голосов
/ 20 февраля 2012

В моем первом ViewController (MonitorViewController) это находится в файле интерфейса MonitorViewController.h:

#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 и ничего больше.

1 Ответ

0 голосов
/ 20 февраля 2012

Я рекомендую использовать 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 также поможет вам с другими распространенными задачами интерфейса отдыха.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...