Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

开放loadDataWithParams实例方法 #35

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CTNetworking.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,8 @@
4A1E17A02045585A00BDBF7B /* BaseAPIManager */ = {
isa = PBXGroup;
children = (
4A1E17A12045585A00BDBF7B /* CTAPIBaseManager.m */,
4A1E17A22045585A00BDBF7B /* CTAPIBaseManager.h */,
4A1E17A12045585A00BDBF7B /* CTAPIBaseManager.m */,
);
path = BaseAPIManager;
sourceTree = "<group>";
Expand Down
2 changes: 1 addition & 1 deletion CTNetworking/CTNetworking/CTNetworkingDefines.h
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ extern NSString * _Nonnull const kCTApiProxyValidateResultKeyResponseString;
@optional
- (void)cleanData;
- (NSDictionary *_Nullable)reformParams:(NSDictionary *_Nullable)params;
- (NSInteger)loadDataWithParams:(NSDictionary *_Nullable)params;
- (NSString *_Nonnull)loadDataWithParams:(NSDictionary *_Nullable)params;

@end

Expand Down
6 changes: 4 additions & 2 deletions CTNetworking/CTNetworking/Components/APIProxy/CTApiProxy.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ typedef void(^CTCallback)(CTURLResponse *response);

+ (instancetype)sharedInstance;

- (NSNumber *)callApiWithRequest:(NSURLRequest *)request success:(CTCallback)success fail:(CTCallback)fail;
- (void)cancelRequestWithRequestID:(NSNumber *)requestID;
- (NSString *)callApiWithRequest:(NSURLRequest *)request success:(CTCallback)success fail:(CTCallback)fail;
- (void)cancelRequestWithRequestID:(NSString *)requestID;
- (void)cancelRequestWithRequestIDList:(NSArray *)requestIDList;

- (void)cancelAllRequests;

@end
64 changes: 55 additions & 9 deletions CTNetworking/CTNetworking/Components/APIProxy/CTApiProxy.m
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#import "NSString+AXNetworkingMethods.h"
#import "NSObject+AXNetworkingMethods.h"
#import "CTMediator+CTAppContext.h"
#import <pthread/pthread.h>

static NSString * const kAXApiProxyDispatchItemKeyCallbackSuccess = @"kAXApiProxyDispatchItemCallbackSuccess";
static NSString * const kAXApiProxyDispatchItemKeyCallbackFail = @"kAXApiProxyDispatchItemCallbackFail";
Expand All @@ -23,13 +24,30 @@
//NSString * const kCTApiProxyValidateResultKeyResponseData = @"kCTApiProxyValidateResultKeyResponseData";

@interface CTApiProxy ()
{
pthread_rwlock_t _dispatchTableLock;
}

@property (nonatomic, strong) NSMutableDictionary *dispatchTable;
@property (nonatomic, strong) NSNumber *recordedRequestId;
//@property (nonatomic, strong) NSNumber *recordedRequestId;

@end

@implementation CTApiProxy

- (instancetype)init
{
self = [super init];
if (self) {
pthread_rwlock_init(&_dispatchTableLock, NULL);
}
return self;
}

- (void)dealloc {
pthread_rwlock_destroy(&_dispatchTableLock);
}

#pragma mark - getters and setters
- (NSMutableDictionary *)dispatchTable
{
Expand All @@ -51,6 +69,12 @@ - (AFHTTPSessionManager *)sessionManagerWithService:(id<CTServiceProtocol>)servi
return sessionManager;
}

- (NSString *)requestIDWithService:(id<CTServiceProtocol>)service dataTask:(NSURLSessionDataTask *)dataTask {
NSString *requestId = [NSString stringWithFormat:@"%@-%ld", NSStringFromClass(service.class), [dataTask taskIdentifier]];

return requestId;
}

#pragma mark - life cycle
+ (instancetype)sharedInstance
{
Expand All @@ -63,31 +87,50 @@ + (instancetype)sharedInstance
}

#pragma mark - public methods
- (void)cancelRequestWithRequestID:(NSNumber *)requestID

- (void)cancelAllRequests
{
pthread_rwlock_wrlock(&_dispatchTableLock);

[self.dispatchTable enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key,
NSURLSessionDataTask * _Nonnull obj,
BOOL * _Nonnull stop) {
[obj cancel];
}];
[self.dispatchTable removeAllObjects];

pthread_rwlock_unlock(&_dispatchTableLock);
}

- (void)cancelRequestWithRequestID:(NSString *)requestID
{
pthread_rwlock_wrlock(&_dispatchTableLock);
NSURLSessionDataTask *requestOperation = self.dispatchTable[requestID];
[requestOperation cancel];
[self.dispatchTable removeObjectForKey:requestID];
pthread_rwlock_unlock(&_dispatchTableLock);
}

- (void)cancelRequestWithRequestIDList:(NSArray *)requestIDList
{
for (NSNumber *requestId in requestIDList) {
for (NSString *requestId in requestIDList) {
[self cancelRequestWithRequestID:requestId];
}
}

/** 这个函数存在的意义在于,如果将来要把AFNetworking换掉,只要修改这个函数的实现即可。 */
- (NSNumber *)callApiWithRequest:(NSURLRequest *)request success:(CTCallback)success fail:(CTCallback)fail
- (NSString *)callApiWithRequest:(NSURLRequest *)request success:(CTCallback)success fail:(CTCallback)fail
{
// 跑到这里的block的时候,就已经是主线程了。
__block NSURLSessionDataTask *dataTask = nil;
dataTask = [[self sessionManagerWithService:request.service] dataTaskWithRequest:request
uploadProgress:nil
downloadProgress:nil
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSNumber *requestID = @([dataTask taskIdentifier]);
uploadProgress:nil
downloadProgress:nil
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSString *requestID = [self requestIDWithService:request.service dataTask:dataTask];
pthread_rwlock_wrlock(&_dispatchTableLock);
[self.dispatchTable removeObjectForKey:requestID];
pthread_rwlock_unlock(&_dispatchTableLock);

NSDictionary *result = [request.service resultWithResponseObject:responseObject response:response request:request error:&error];
// 输出返回数据
Expand All @@ -110,9 +153,12 @@ - (NSNumber *)callApiWithRequest:(NSURLRequest *)request success:(CTCallback)suc
}
}];

NSNumber *requestId = @([dataTask taskIdentifier]);
NSString *requestId = [self requestIDWithService:request.service dataTask:dataTask];

pthread_rwlock_wrlock(&_dispatchTableLock);
self.dispatchTable[requestId] = dataTask;
pthread_rwlock_unlock(&_dispatchTableLock);

[dataTask resume];

return requestId;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,13 @@
@property (nonatomic, assign, readonly) BOOL isLoading;

// start
- (NSInteger)loadData;
+ (NSInteger)loadDataWithParams:(NSDictionary * _Nullable)params success:(void (^ _Nullable)(CTAPIBaseManager * _Nonnull apiManager))successCallback fail:(void (^ _Nullable)(CTAPIBaseManager * _Nonnull apiManager))failCallback;
- (NSString *_Nonnull)loadData;
- (NSString *_Nonnull)loadDataWithParams:(NSDictionary * _Nullable)params success:(void (^ _Nullable)(CTAPIBaseManager * _Nonnull apiManager))successCallback fail:(void (^ _Nullable)(CTAPIBaseManager * _Nonnull apiManager))failCallback;
+ (NSString *_Nonnull)loadDataWithParams:(NSDictionary * _Nullable)params success:(void (^ _Nullable)(CTAPIBaseManager * _Nonnull apiManager))successCallback fail:(void (^ _Nullable)(CTAPIBaseManager * _Nonnull apiManager))failCallback;

// cancel
- (void)cancelAllRequests;
- (void)cancelRequestWithRequestId:(NSInteger)requestID;
- (void)cancelRequestWithRequestId:(NSString *_Nonnull)requestID;

// finish
- (id _Nullable )fetchDataWithReformer:(id <CTAPIManagerDataReformer> _Nullable)reformer;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
#import "CTMediator+CTAppContext.h"
#import "CTServiceFactory.h"

#import <pthread/pthread.h>


NSString * const kCTUserTokenInvalidNotification = @"kCTUserTokenInvalidNotification";
NSString * const kCTUserTokenIllegalNotification = @"kCTUserTokenIllegalNotification";

Expand All @@ -23,6 +26,9 @@


@interface CTAPIBaseManager ()
{
pthread_rwlock_t _requestIdListLock;
}

@property (nonatomic, strong, readwrite) id fetchedRawData;
@property (nonatomic, assign, readwrite) BOOL isLoading;
Expand Down Expand Up @@ -55,6 +61,8 @@ - (instancetype)init
_memoryCacheSecond = 3 * 60;
_diskCacheSecond = 3 * 60;

pthread_rwlock_init(&_requestIdListLock, NULL);

if ([self conformsToProtocol:@protocol(CTAPIManager)]) {
self.child = (id <CTAPIManager>)self;
} else {
Expand All @@ -68,7 +76,9 @@ - (instancetype)init
- (void)dealloc
{
[self cancelAllRequests];
self.requestIdList = nil;
_requestIdList = nil;

pthread_rwlock_destroy(&_requestIdListLock);
}

#pragma mark - NSCopying
Expand All @@ -81,13 +91,16 @@ - (id)copyWithZone:(NSZone *)zone
- (void)cancelAllRequests
{
[[CTApiProxy sharedInstance] cancelRequestWithRequestIDList:self.requestIdList];

pthread_rwlock_wrlock(&_requestIdListLock);
[self.requestIdList removeAllObjects];
pthread_rwlock_unlock(&_requestIdListLock);
}

- (void)cancelRequestWithRequestId:(NSInteger)requestID
- (void)cancelRequestWithRequestId:(NSString *)requestID
{
[self removeRequestIdWithRequestID:requestID];
[[CTApiProxy sharedInstance] cancelRequestWithRequestID:@(requestID)];
[[CTApiProxy sharedInstance] cancelRequestWithRequestID:requestID];
}

- (id)fetchDataWithReformer:(id<CTAPIManagerDataReformer>)reformer
Expand All @@ -102,29 +115,29 @@ - (id)fetchDataWithReformer:(id<CTAPIManagerDataReformer>)reformer
}

#pragma mark - calling api
- (NSInteger)loadData
- (NSString *)loadData
{
NSDictionary *params = [self.paramSource paramsForApi:self];
NSInteger requestId = [self loadDataWithParams:params];
NSString *requestId = [self loadDataWithParams:params];
return requestId;
}

+ (NSInteger)loadDataWithParams:(NSDictionary *)params success:(void (^)(CTAPIBaseManager *))successCallback fail:(void (^)(CTAPIBaseManager *))failCallback
+ (NSString *)loadDataWithParams:(NSDictionary *)params success:(void (^)(CTAPIBaseManager *))successCallback fail:(void (^)(CTAPIBaseManager *))failCallback
{
return [[[self alloc] init] loadDataWithParams:params success:successCallback fail:failCallback];
}

- (NSInteger)loadDataWithParams:(NSDictionary *)params success:(void (^)(CTAPIBaseManager *))successCallback fail:(void (^)(CTAPIBaseManager *))failCallback
- (NSString *)loadDataWithParams:(NSDictionary *)params success:(void (^)(CTAPIBaseManager *))successCallback fail:(void (^)(CTAPIBaseManager *))failCallback
{
self.successBlock = successCallback;
self.failBlock = failCallback;

return [self loadDataWithParams:params];
}

- (NSInteger)loadDataWithParams:(NSDictionary *)params
- (NSString *)loadDataWithParams:(NSDictionary *)params
{
NSInteger requestId = 0;
NSString *requestId = @"";
NSDictionary *reformedParams = [self reformParams:params];
if (reformedParams == nil) {
reformedParams = @{};
Expand Down Expand Up @@ -158,7 +171,7 @@ - (NSInteger)loadDataWithParams:(NSDictionary *)params
request.service = service;
[CTLogger logDebugInfoWithRequest:request apiName:self.child.methodName service:service];

NSNumber *requestId = [[CTApiProxy sharedInstance] callApiWithRequest:request success:^(CTURLResponse *response) {
NSString *requestId = [[CTApiProxy sharedInstance] callApiWithRequest:request success:^(CTURLResponse *response) {
[self successedOnCallingAPI:response];
} fail:^(CTURLResponse *response) {
CTAPIManagerErrorType errorType = CTAPIManagerErrorTypeDefault;
Expand All @@ -173,12 +186,15 @@ - (NSInteger)loadDataWithParams:(NSDictionary *)params
}
[self failedOnCallingAPI:response withErrorType:errorType];
}];

pthread_rwlock_wrlock(&_requestIdListLock);
[self.requestIdList addObject:requestId];
pthread_rwlock_unlock(&_requestIdListLock);

NSMutableDictionary *params = [reformedParams mutableCopy];
params[kCTAPIBaseManagerRequestID] = requestId;
[self afterCallingAPIWithParams:params];
return [requestId integerValue];
return requestId;

} else {
[self failedOnCallingAPI:nil withErrorType:CTAPIManagerErrorTypeNoNetWork];
Expand Down Expand Up @@ -405,17 +421,21 @@ - (NSDictionary *)reformParams:(NSDictionary *)params
}

#pragma mark - private methods
- (void)removeRequestIdWithRequestID:(NSInteger)requestId
- (void)removeRequestIdWithRequestID:(NSString *)requestId
{
NSNumber *requestIDToRemove = nil;
for (NSNumber *storedRequestId in self.requestIdList) {
if ([storedRequestId integerValue] == requestId) {
pthread_rwlock_wrlock(&_requestIdListLock);

NSString *requestIDToRemove = nil;
for (NSString *storedRequestId in self.requestIdList) {
if ([storedRequestId isEqualToString:requestId]) {
requestIDToRemove = storedRequestId;
}
}
if (requestIDToRemove) {
[self.requestIdList removeObject:requestIDToRemove];
}

pthread_rwlock_unlock(&_requestIdListLock);
}

#pragma mark - getters and setters
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ typedef NS_ENUM(NSUInteger, CTURLResponseStatus)
@property (nonatomic, assign, readonly) CTURLResponseStatus status;
@property (nonatomic, copy, readonly) NSString *contentString;
@property (nonatomic, copy, readonly) id content;
@property (nonatomic, assign, readonly) NSInteger requestId;
@property (nonatomic, copy, readonly) NSString *requestId;
@property (nonatomic, copy, readonly) NSURLRequest *request;
@property (nonatomic, copy, readonly) NSData *responseData;
@property (nonatomic, strong, readonly) NSString *errorMessage;
Expand All @@ -32,7 +32,7 @@ typedef NS_ENUM(NSUInteger, CTURLResponseStatus)

@property (nonatomic, assign, readonly) BOOL isCache;

- (instancetype)initWithResponseString:(NSString *)responseString requestId:(NSNumber *)requestId request:(NSURLRequest *)request responseObject:(id)responseObject error:(NSError *)error;
- (instancetype)initWithResponseString:(NSString *)responseString requestId:(NSString *)requestId request:(NSURLRequest *)request responseObject:(id)responseObject error:(NSError *)error;

// 使用initWithData的response,它的isCache是YES,上面两个函数生成的response的isCache是NO
- (instancetype)initWithData:(NSData *)data;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ @interface CTURLResponse ()
@property (nonatomic, copy, readwrite) NSString *contentString;
@property (nonatomic, copy, readwrite) id content;
@property (nonatomic, copy, readwrite) NSURLRequest *request;
@property (nonatomic, assign, readwrite) NSInteger requestId;
@property (nonatomic, copy, readwrite) NSString *requestId;
@property (nonatomic, copy, readwrite) NSData *responseData;
@property (nonatomic, assign, readwrite) BOOL isCache;
@property (nonatomic, strong, readwrite) NSString *errorMessage;
Expand All @@ -26,12 +26,12 @@ @interface CTURLResponse ()
@implementation CTURLResponse

#pragma mark - life cycle
- (instancetype)initWithResponseString:(NSString *)responseString requestId:(NSNumber *)requestId request:(NSURLRequest *)request responseObject:(NSDictionary *)responseObject error:(NSError *)error
- (instancetype)initWithResponseString:(NSString *)responseString requestId:(NSString *)requestId request:(NSURLRequest *)request responseObject:(NSDictionary *)responseObject error:(NSError *)error
{
self = [super init];
if (self) {
self.contentString = [responseString CT_defaultValue:@""];
self.requestId = [requestId integerValue];
self.requestId = requestId;
self.request = request;
self.acturlRequestParams = request.actualRequestParams;
self.originRequestParams = request.originRequestParams;
Expand All @@ -49,7 +49,7 @@ - (instancetype)initWithData:(NSData *)data
if (self) {
self.contentString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
self.status = [self responseStatusWithError:nil];
self.requestId = 0;
self.requestId = @"";
self.request = nil;
self.responseData = data;
self.content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL];
Expand Down
Loading