1. 程式人生 > >AFNetworking原始碼閱讀筆記 1

AFNetworking原始碼閱讀筆記 1

1.專案使用AFNetworking,一直封裝為工具類使用,20180911更新了新版本,對此做初略研究

1.1 使用案列:

    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer = [AFHTTPRequestSerializer serializer];

    NSMutableSet *acceptableSet = [NSMutableSet setWithSet:mgr.responseSerializer.acceptableContentTypes
]; [acceptableSet addObject:@"text/html"]; AFJSONResponseSerializer *jsonResponse = [AFJSONResponseSerializer serializer]; jsonResponse.removesKeysWithNullValues = YES; jsonResponse.acceptableContentTypes = acceptableSet; mgr.responseSerializer = jsonResponse; // 2.傳送請求 [mgr POST:url parameters:params headers:nil
progress:^(NSProgress * _Nonnull uploadProgress) { } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { if (success) { ResultStatus result = 0; if ([responseObject[@"result"] isKindOfClass:[NSString class]]) { // if result is NSString
result = empty(responseObject[@"result"]) ? 0 : [responseObject[@"result"] integerValue]; } else if ([responseObject[@"result"] isKindOfClass:[NSNumber class]]) { // if result is NSNumber result = [responseObject[@"result"] intValue] == 1 ? ResultStatusSuccess : ResultStatusFailure; } success(result, responseObject); } // 刪除迴圈引用 [mgr invalidateSessionCancelingTasks:YES]; } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { if (failure) { failure(error); } // 刪除迴圈引用 [mgr invalidateSessionCancelingTasks:YES]; }];

2.管理類Manager:

2.1 繼承關係

 AFHTTPSessionManager : AFURLSessionManager : NSObject 

2.2 實現代理方法:

<NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSSecureCoding, NSCopying>

2.3 主要使用AFHTTPSessionManager,

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

manager 主要建立一系列預設配置,主要有執行緒,請求配置,詳情配置,安全配置,連線配置,鎖, NSURLSession

    if (!configuration) {
        configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    }

    self.sessionConfiguration = configuration;

    self.operationQueue = [[NSOperationQueue alloc] init];
    self.operationQueue.maxConcurrentOperationCount = 1;

    self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue];

    self.responseSerializer = [AFJSONResponseSerializer serializer];

    self.securityPolicy = [AFSecurityPolicy defaultPolicy];

#if !TARGET_OS_WATCH
    self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
#endif

    self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init];

    self.lock = [[NSLock alloc] init];
    self.lock.name = AFURLSessionManagerLockName;

    [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
        for (NSURLSessionDataTask *task in dataTasks) {
            [self addDelegateForDataTask:task uploadProgress:nil downloadProgress:nil completionHandler:nil];
        }

        for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
            [self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil];
        }

        for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
            [self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil];
        }
    }];

2.4 可配置manager requestSerializer 及 responseSerializer

2.5 manage 可直接呼叫post get請求方法,通過block獲取資料

- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
                             parameters:(nullable id)parameters
                                headers:(nullable NSDictionary <NSString *, NSString *> *)headers
                               progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
                                success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                                failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;

- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString
                            parameters:(nullable id)parameters
                               headers:(nullable NSDictionary <NSString *, NSString *> *)headers
                              progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress
                               success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                               failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;

post請求使用NSMutableURLRequest

NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];

post請求返回資料處理

    __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
        if (error) {
            if (failure) {
                failure(task, error);
            }
        } else {
            if (success) {
                success(task, responseObject);
            }
        }
    }];