Skip to content

Instantly share code, notes, and snippets.

@kazuph kazuph/Hoge.h
Created Aug 16, 2014

Embed
What would you like to do?
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
You can’t perform that action at this time.