Skip to content

Instantly share code, notes, and snippets.

@kazuph
Created August 16, 2014 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazuph/0a3528a3ef58e3379a06 to your computer and use it in GitHub Desktop.
Save kazuph/0a3528a3ef58e3379a06 to your computer and use it in GitHub Desktop.
AFNetworkingをViewControllerに書かないでModelに書きたいとき ref: http://qiita.com/kazuph/items/2cc92622a298079aad5e
#import "AFHTTPSessionManager.h"
@interface Hoge : NSObject
+ (Hoge*)sharedClient;
- (void)hogeWithId:(NSString *)hogeId completion:(void (^)(NSDictionary *results, NSError *error))block;
@end
#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
#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 {
// 失敗時の処理
}
}];
}
<略>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment