AFNetworking, as read in this article, is version 3.2.0.

This classification provides a means of controlling the request cycle, including progress monitoring, success and failure callbacks.

1. Interface file

1.1. The attribute

/** network sessionManager object */ @property (nonatomic, strong) AFHTTPSessionManager *sessionManager;Copy the code

Method of 1.2.

/** loadRequest:(NSURLRequest *)request progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success failure:(nullable void (^)(NSError *error))failure; /** asynchronously loads the specified request with the specified MIME type and the specified text encoding format */ - (void)loadRequest:(NSURLRequest *)request MIMEType:(nullable NSString *)MIMEType textEncodingName:(nullable NSString *)textEncodingName progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success failure:(nullable void (^)(NSError *error))failure;Copy the code

2.UIWebView+_AFNetworking private classification

2.1. The interface

/** Save task object */ @property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask;Copy the code

2.2. To achieve

The two methods are to save task objects by adding attributes to the classes through the Runtime’s associated objects

- (NSURLSessionDataTask *)af_URLSessionTask {
    return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask));
}

- (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask {
    objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
Copy the code

3. Method implementation

  • Property

The following four methods also add a genus to the classification by associating objects, respectively the save network session manager object and the response serialization object

- (AFHTTPSessionManager *)sessionManager { static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _af_defaultHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration  defaultSessionConfiguration]]; _af_defaultHTTPSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer]; _af_defaultHTTPSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer]; });returnobjc_getAssociatedObject(self, @selector(sessionManager)) ? : _af_defaultHTTPSessionManager; } - (void)setSessionManager:(AFHTTPSessionManager *)sessionManager {
    objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
    static AFHTTPResponseSerializer <AFURLResponseSerialization> *_af_defaultResponseSerializer = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer];
    });

    returnobjc_getAssociatedObject(self, @selector(responseSerializer)) ? : _af_defaultResponseSerializer; } - (void)setResponseSerializer:(AFHTTPResponseSerializer<AFURLResponseSerialization> *)responseSerializer {
    objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
Copy the code
  • Interface method implementation
- (void)loadRequest:(NSURLRequest *)request progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success failure:(void (^)(NSError *error))failure {// Call the following method [self loadRequest:request MIMEType:nil textEncodingName:nil progress:progress success:^NSData *(NSHTTPURLResponse *response, NSData *data) {// Set the character encoding mode to UTF8 NSStringEncoding stringEncoding = NSUTF8StringEncoding; // If the response object has a text encoding, set the character encoding to the text encoding of the responseif (response.textEncodingName) {
            CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
            if(encoding ! = kCFStringEncodingInvalidId) { stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); }} // Encode the returned data NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding]; // Block is called to pass data if a success callback is setif(success) { string = success(response, string); } // Encode the string into binary data and return itreturn[string dataUsingEncoding:stringEncoding]; } failure:failure]; } - (void)loadRequest:(NSURLRequest *)request MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success failure:(void (^)(NSError *error))failure {// crash NSParameterAssert(request) when there is no argument in debug mode; // If a task is currently in progress or has been paused, cancel the task and empty the properties that save itif(self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) { [self.af_URLSessionTask cancel]; } self.af_URLSessionTask = nil; // Generate task __weak __typeof(self)weakSelf = self; __block NSURLSessionDataTask *dataTask; dataTask = [self.sessionManager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nonnull responseObject, NSError * _Nullable error) {__strong __typeof(weakSelf) strongSelf = weakSelf; // Call failure callback block if error occursif (error) {
                        if(failure) { failure(error); } // If successful}else{// Call the successful callback block firstif(success) { success((NSHTTPURLResponse *)response, responseObject); } / / call the UIWebView loading local data in a way that load pages [strongSelf loadData: responseObject MIMEType: MIMEType textEncodingName: textEncodingName baseURL:[dataTask.currentRequest URL]]; // Call the complete load method in the UIWebView proxyif([strongSelf.delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) { [strongSelf.delegate webViewDidFinishLoad:strongSelf]; }}}]; // Save the task object self.af_urlsessionTask = dataTask; // If the progress object is set, the download process object of the network session manager is obtainedif(progress ! = nil) { *progress = [self.sessionManager downloadProgressForTask:dataTask]; } // Start task [self.af_urlsessionTask resume]; // Call the start load method in the UIWebView proxyif ([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
        [self.delegate webViewDidStartLoad:self];
    }

Copy the code

4. To summarize

After looking at the source code for this class, we can see that what this class does is manually implement the process of loading network data from UIWebView, so that we can listen for progress and handle success and failure results through block callbacks.

Typically, we load a specified page using the loadRequest: method, and then listen for the start, end, and failure of the page load using methods in UIWebViewDelegate.

The AFHTTPSessionManager class manually generates the NSURLSessionDataTask object to download the binary data of the web page, and then loadData: MIMEType: textEncodingName: The baseURL: method loads the binary data of a web page that has been downloaded locally. In this process, progress monitoring, success and failure callbacks are implemented through methods already implemented in the AFHTTPSessionManager class.

AFNetworking

AFNetworking (A) — Start using it

Source: reading AFNetworking (2) — AFURLRequestSerialization

Source: reading AFNetworking (3) — AFURLResponseSerialization

AFNetworking (4) — AFSecurityPolicy

Source: reading AFNetworking (5) — AFNetworkReachabilityManager

AFNetworking (6) — Afurlssession Manager

AFNetworking (7) — Afhttpssession Manager

AFNetworking (8) – AFAutoPurgingImageCache

AFNetworking (9) — AFImageDownloader

The source code to read: AFNetworking (10) — AFNetworkActivityIndicatorManager

AFNetworking — UIActivityIndicatorView+AFNetworking

AFNetworking (12) — UIButton+AFNetworking

AFNetworking (13) — UIImageView+AFNetworking

UIProgressView+AFNetworking

AFNetworking — UIRefreshControl+AFNetworking

UIWebView+AFNetworking