1

AFnetworking から RestKit に切り替えました。AFnetworking には API クラスがありました。API.h クラスには以下が含まれていました。

#import <UIKit/UIKit.h>
typedef void (^JSONResponseBlock)(NSDictionary* json);
@interface API : NSObject
//the authorized user
@property (strong, nonatomic) NSDictionary* user;

+(API*)sharedInstance;
//check whether there's an authorized user

//send an API command to the server
-(void)loginCommand:(NSMutableDictionary*)params onCompletion:(JSONResponseBlock)completionBlock;

そして、私の API.m クラスは次のようになります。

+(API *)sharedInstance
{
    static API *sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^ {
        sharedInstance = [[self alloc]initWithBaseURL:[NSURL URLWithString:kAPIHost]];
    });
    return sharedInstance;
}

#pragma mark - init
//intialize the API class with the destination host name

-(API *)init
{
    //call super init
    self = [super init];

    if (self != nil){
        //initialize the object
        user = nil;

        [self registerHTTPOperationClass:[AFJSONRequestOperation class]];

        // Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
        [self setDefaultHeader:@"Accept" value:@"application/json"];
    }
    return self;
}

-(void)loginCommand:(NSMutableDictionary *)params onCompletion:(JSONResponseBlock)completionBlock{
    NSLog(@"%@%@",kAPIHost,kAPILogin);
    NSMutableURLRequest *apiRequest = [self multipartFormRequestWithMethod:@"POST" path:kAPILogin parameters:params constructingBodyWithBlock:^(id <AFMultipartFormData>formData){
        //TODO: attach file if needed

    }];
    AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:apiRequest];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
        //success!
        NSLog(@"SUCCESSSS!");
        completionBlock(responseObject);
    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        //Failure
        NSLog(@"FAILUREE!");
        completionBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:@"error"]);
    }];
    [operation start];

}

ご覧のとおり、一度だけインスタンス化し、すべてのメソッドをここに配置します。私のView Controllerでは、このメソッドをパラメーター辞書で呼び出すだけです。次に、JSON ファイル全体を読み取ることができました。

現在、restKit を使用して、これをすべて viewController レベルで行います。AFNetworking のように分割したいと思います。これは私がRestKitで行っていることです。現時点では、これはすべてviewControllerレベルです。

   //let AFNetworking manage the activity indicator
[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

// Initialize HTTPClient
NSURL *baseURL = [NSURL URLWithString:@"http://virtuele-receptie.preview.sanmax.be"];
AFHTTPClient* client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
//we want to work with JSON-Data
[client setDefaultHeader:@"Accept" value:RKMIMETypeJSON];

// Initialize RestKit
RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];


//Do mapping

RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:dataMapping
                                                                                   pathPattern:nil
                                                                                       keyPath:@"data"
                                                                                   statusCodes:[NSIndexSet indexSetWithIndex:200]];
[objectManager addResponseDescriptor:responseDescriptor];

NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:_txtLogin.text,@"email",_txtPass.text,@"pwd", nil];

[objectManager getObject:nil path:@"/nl/webservice/company-user/login/apikey/key12345678" parameters:dict
                 success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                   //Success  
                 }
                 failure:^(RKObjectRequestOperation *operation, NSError *error) {
                     //Failure
                 }];
4

1 に答える 1

0

これまでのところ、RestKit に関しては、他の HTTP フレームワークで作成するような API クラスの必要性はあまり見られませんでした。RestKit には独自の HTTP クライアント (実際には、AFNetworking のクライアントのみ) があるため、HTTP クライアント用のクラスを用意する必要はありません。また、RKObjectManager を使用するたびに、通常はメソッド パラメーターにアクセスしてコールバックをブロックする必要があることがわかりました。各View Controller内。言い換えれば、RestKit ネットワーク コードを API クラスで実行したくありません。ビュー コントローラー (成功ブロック、失敗ブロックなど) でアクセスできるメソッドで呼び出し全体を本質的にラップする必要があるからです。

本質的に、RestKit の設計はネットワーク コードを非常に軽量化するので、私の経験では (現在 3 つまたは 4 つのアプリ)、あなたが説明したような API クラスを作成する十分な理由をまだ見ていません。

于 2013-12-02T20:00:34.927 に答える