当前位置:网站首页>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 .
边栏推荐
- Junior network security engineers master these penetration methods and steadily improve their technology to become leaders!
- How long can the trademark registration be completed? How to improve the speed of trademark registration?
- Tencent cloud won the first place in the cloud natural language understanding classification task
- Super parameter tuning of neural network using keras tuner
- Build your own cloud game server. What if the cloud game server is attacked
- UNIX command encyclopedia, common commands are here, work must!
- Learning and life -- Talking about my learning methods
- Initial experience of creating partitioned tables under MySQL cases tdsql for MySQL (I)
- If there are enumerations in the entity object, the conversion of enumerations can be carried out with @jsonvalue and @enumvalue annotations
- What are the conditions for trademark registration? How long does it take to register a trademark?
猜你喜欢

163 mailbox login portal display, enterprise mailbox computer version login portal
Cloudpods golang practice

application. Yaml configuring multiple running environments

BIM model example

Leetcode969: pancake sorting (medium, dynamic programming)

Advanced BOM tool intelligent packaging function

If there are enumerations in the entity object, the conversion of enumerations can be carried out with @jsonvalue and @enumvalue annotations

How to fill in and register e-mail, and open mass mailing software for free

2020 language and intelligent technology competition was launched, and Baidu provided the largest Chinese data set

Introduction to development model + test model
随机推荐
Buddha's foot before examination: the second play of leetcode
[Tencent cloud double 12 audio and video communication special session] from 9 yuan for Q4 counter attack artifact, SMS and security (New) package!
Are cloud game servers expensive to rent? Factors to consider in cloud game server leasing
UNIX command encyclopedia, common commands are here, work must!
How to build your own website? Is it difficult?
Buddha's foot before examination: the first bullet of leetcode
Is it illegal to use someone else's trademark to register a domain name? What should we pay attention to when registering a domain name?
Tornado code for file download
Hungry? Remote dual live database practice
Operation and maintenance platform tcapulusdb transaction management
How to solve the problem of uncaught (in promise) when easywasmlayer plays a video?
Do you still understand the deadlock handling methods in MySQL performance testing and tuning?
Implementing cos signature with postman
Echo framework: add tracing Middleware
Measurement model 𞓜 pre determined variable # time Fe
The new purchased machines with large customized images are slow to enter the system
Buddha's foot before examination: the third bullet of leetcode
Set multiple print for batch generated barcodes
Tencent cloud won the first place in the cloud natural language understanding classification task
What is a port? The most complete and strongest port number in history, collection!