当前位置:网站首页>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 .
边栏推荐
- How to calculate the trademark registration fee? How much does it cost to register a trademark?
- Measurement model 𞓜 pre determined variable # time Fe
- What information should be provided for enterprise trademark registration? Is it difficult to register a trademark?
- Do you still understand the deadlock handling methods in MySQL performance testing and tuning?
- [security] Tencent cloud double 12 is not limited to new and old users! Safe sub venue - discount guide! Unlimited account types!
- SQL Server database recovery case analysis
- Select problem set 3
- Buddha's foot before examination: the second play of leetcode
- How do I fix the iPhone green screen problem? Try these solutions
- What are the main functions of DNS? What are the benefits of IP address translation
猜你喜欢

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

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

application. Yaml configuring multiple running environments

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

BIM model example

Introduction to development model + test model

Advanced BOM tool intelligent packaging function
Cloudpods golang practice

163 mailbox login portal display, enterprise mailbox computer version login portal

Leetcode969: pancake sorting (medium, dynamic programming)
随机推荐
Buddha's foot before examination: the second play of leetcode
How long can the trademark registration be completed? How to improve the speed of trademark registration?
Vivo global mall: design and practice of commodity system architecture
What are the main functions of DNS? What are the benefits of IP address translation
Gin framework: adding tracing Middleware
What is a private VLAN? Eight part essay with pictures and texts.
How to build a website? What needs attention?
How do I fix the iPhone green screen problem? Try these solutions
How to quickly handle third-party login and easy to expand?
Shopify has quietly taken the second place in e-commerce in North America. Is independent station the "magic weapon" to win?
NTP synchronization clock server server and client settings
Question: can you get download the resources of Baidu online disk?
[supply chain • case] Tianneng group: the key to understanding the leading battery manufacturer to achieve the first profit fault
Benchmarking Shopify? Similarities and differences between "two giants" of Chinese e-commerce SAAS and Weimeng
Facebook was officially renamed meta, and the digital twin meta universe was applied!
How many graphics cards are required for cloud game servers? What should be paid attention to when purchasing servers
How to bind EIP to access public network in tke cluster fixed IP mode pod
How to build a website? These things should be paid attention to
How to formulate a domain name trademark registration scheme? What if the plan is rejected?
[new features] Tencent cloud lightweight ECS will soon support attaching data disks!!!