LoginSignup
8
8

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-08-16

ってどうしてます?

自分は以下に示すようにやっているのですが、良い・悪い判断できないのでコメントいただけると助かります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 {
             // 失敗時の処理
         }
     }];
}

<>

8
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8