AFNetworkingの処理をViewControllerに書かないでModelに書きたいとき

More than 3 years have passed since last update.

ってどうしてます?

自分は以下に示すようにやっているのですが、良い・悪い判断できないのでコメントいただけると助かりますm(_ _)m


Model


Hoge.h

#import "AFHTTPSessionManager.h"

@interface Hoge : NSObject
+ (Hoge*)sharedClient;
- (void)hogeWithId:(NSString *)hogeId completion:(void (^)(NSDictionary *results, NSError *error))block;
@end


Hoge.m

#import "Hoge.h"

static NSString * const APIBaseURLString = @"http://example.com/";

@implementation Hoge

+ (Hoge*)sharedClient
{
static Hoge* _sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [[Hoge alloc] init];
});
return _sharedClient;
}

- (NSURL *)url
{
return [[NSURL URLWithString:APIBaseURLString] URLByAppendingPathComponent:@"api/hoges"];
}

- (void)hogeWithId:(NSString *)hogeId completion:(void (^)(NSDictionary *results, NSError *error))block
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:[[self url] absoluteString]
parameters:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
if (block) block(responseObject, nil);
}
failure:^(NSURLSessionDataTask *task, NSError *error) {
if (block) block(nil, error);
}];
}
@end



Controller


MainViewController.m

#import "MainViewController.h"

#import "Hoge.h"

<略>

- (IBAction)getHoge:(id)sender {
NSString* id = _hogeId.text;

[[Authentication sharedClient]
hogeWithId:id
completion:^(NSDictionary *results, NSError *error) { //通信完了時のViewなどの処理はblockにして渡す
if (error) { NSLog(@"Error %@", error); return; }
if ([results[@"success"] isEqual: @(YES)]) {
// 成功時の処理
} else {
// 失敗時の処理
}
}];
}

<略>