当前位置:网站首页>Afnetworking usage and cache processing

Afnetworking usage and cache processing

2022-06-24 02:27:00 User 7705674

AFNetWorking stay IOS It is a third-party open source library that is often used in development , Its best advantage is timely maintenance , Open source .

Commonly used GET And POST Request method :

POST request :

// Initialize a request object  
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
  NSString * url = @" Your request address ";
  //dic  Parameter dictionary 
 [manager POST:url parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
    // Request a successful callback 
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // Request failed callback     
    }];

GET request :

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
 NSString * url = @" Your request address ";
   [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    // Request a successful callback 
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // Request failed callback    
    }];

There is a place to pay attention to ,

[AFHTTPRequestOperationManager manager]

For this class method, we can click into the source code to find :

+ (instancetype)manager {
    return [[self alloc] initWithBaseURL:nil];
}

This initializes a and returns a new object , Not alone .

Use this download method , Data after downloading AFNetWorking Will help us automatically parse , But sometimes the data given by the server is not standard , Then we need to add this setting :

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

In this way, we will get the original HTTP Return us the data .

Let's explore it again , After downloading successfully , What exactly are the parameters in the callback method

success:^(AFHTTPRequestOperation *operation, id responseObject)

among , The second parameter responseObject It was downloaded data data , It can be done directly JSON Equal resolution .

The first parameter , It's a AFHTTPRequestOperation object , Look at the source file

@interface AFHTTPRequestOperation : AFURLConnectionOperation

@property (readonly, nonatomic, strong) NSHTTPURLResponse *response;

@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;

@property (readonly, nonatomic, strong) id responseObject;

@end

You can find , One of the members is responseObject, meanwhile ,AFHTTPRequestOperation It is inherited from AFURLConnectionOperation, We're looking AFURLConnectionOperation This class :

@interface AFURLConnectionOperation : NSOperation <NSURLConnectionDelegate, NSURLConnectionDataDelegate, NSSecureCoding, NSCopying>

@property (nonatomic, strong) NSSet *runLoopModes;

@property (readonly, nonatomic, strong) NSURLRequest *request;

@property (readonly, nonatomic, strong) NSURLResponse *response;

@property (readonly, nonatomic, strong) NSError *error;

@property (readonly, nonatomic, strong) NSData *responseData;

@property (readonly, nonatomic, copy) NSString *responseString;

@property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding;

@property (nonatomic, assign) BOOL shouldUseCredentialStorage;

@property (nonatomic, strong) NSURLCredential *credential;

@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;

@property (nonatomic, strong) NSInputStream *inputStream;

@property (nonatomic, strong) NSOutputStream *outputStream;

@property (nonatomic, strong) dispatch_queue_t completionQueue;

@property (nonatomic, strong) dispatch_group_t completionGroup;

@property (nonatomic, strong) NSDictionary *userInfo;

- (instancetype)initWithRequest:(NSURLRequest *)urlRequest NS_DESIGNATED_INITIALIZER;

- (void)pause;

- (BOOL)isPaused;

- (void)resume;

See here , Just leave AFNETWorking The source of encapsulation is very close , There are a lot of members , It contains most of the information we need , You can get... By clicking grammar , There are input and output streams , error message , The request to the Data data , And the requested string data  

responseString

We can go through

NSLog ( @"operation: %@" , operation. responseString );

To print and view the requested original information .

Some attention :

1. About collapse url by nil

Most of these reasons are url There are special characters or Chinese characters in ,AFNETWorking I didn't do it UTF8 Transcoding of , need :

url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

2. add to HttpHead Method of field

 // For this download task HTTP Head add @"User-Agent" Field 
 [manager.requestSerializer setValue:_scrData forHTTPHeaderField:@"User-Agent"];
 // Print head information 
    NSLog(@"%@",manager.requestSerializer.HTTPRequestHeaders);

In the download request , Often request some data that doesn't change long , If every time APP Start all requests , It will consume a lot of resources , And sometimes cache processing , Can greatly improve the user experience .

stay AFNETWorking in , There is no ready-made caching scheme , We can write files , Make your own cache .

In the download method :

[manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        // Write cache 
        NSString *cachePath = @" Your cache path ";//  /Library/Caches/MyCache
        [data writeToFile:cachePath atomically:YES];
                succsee(data);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];

Then before each download , Make the following judgments :

 NSString * cachePath = @" Your cache path ";
        if ([[NSFileManager defaultManager] fileExistsAtPath:cachePath]) {
            // Read cache files locally 
            NSData *data = [NSData dataWithContentsOfFile:cachePath];
            }

Sometimes , Our download request may be triggered by the user's action , Like a button . We should also deal with a protection mechanism ,

// Initialize a download request array 
NSArray * requestArray=[[NSMutableArray alloc]init];
// Make the following judgment before each download task 
for (NSString * request in requestArray) {
        if ([url isEqualToString:request]) {
            return;
        }
    }
 [requestArray addObject:url];
 // After the download succeeds or fails 
 [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [requestArray removeObject:url]
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [requestArray removeObject:url]
    }]; 

thus , A comparison is complete AFNETWorking The request usage process is complete .

原网站

版权声明
本文为[User 7705674]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/10/20211029145342138X.html