用RAC封装AFN

2017-12-28  本文已影响207人  _moses
#import <AFNetworking/AFNetworking.h>
#import <ReactiveObjC/ReactiveObjC.h>

@interface MSHTTPRequest : AFHTTPSessionManager

+ (instancetype _Nonnull)shareInstace;

- (RACSignal * _Nonnull)POST:(NSString * _Nonnull)URLString parameters:(NSDictionary * _Nullable)parameters;

@end
#import "MSHTTPRequest.h"

static id _instace;

@implementation MSHTTPRequest

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instace = [super allocWithZone:zone];
    });
    return _instace;
}

+ (instancetype)shareInstace {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instace = [[self alloc] initWithBaseURL:nil];
    });
    return _instace;
}

- (id)copyWithZone:(NSZone *)zone {
    return _instace;
}

- (RACSignal * _Nonnull)POST:(NSString * _Nonnull)URLString parameters:(NSDictionary * _Nullable)parameters {
    return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [self POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [subscriber sendNext:responseObject];
            [subscriber sendCompleted];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [subscriber sendError:error];
        }];
        return nil;
    }];
}

@end
[[[MSHTTPRequest shareInstace] POST:@"url" parameters:nil] subscribeNext:^(id  _Nullable x) {
    NSLog(@"%@", x);
} error:^(NSError * _Nullable error) {
    NSLog(@"%@", error);
}];
上一篇下一篇

猜你喜欢

热点阅读