iOS Development. Third Party Network Download Processing Framework: AFNetworking Network Download Processing (Official Document Translation)

click AFNetworking download


1. Framework system

1.1 NSURLSession

  • AFURLSessionManager
  • AFHTTPSessionManager

1.2 serialization

  • <AFURLRequestSerialization>

    • AFHTTPRequestSerializer
    • AFJSONRequestSerializer
    • AFPropertyListRequestSerializer
  • <AFURLResponseSerialization>

    • AFHTTPResponseSerializer
    • AFJSONResponseSerializer
    • AFXMLParserResponseSerializer
    • AFXMLDocumentResponseSerializer (Mac OS X)
    • AFPropertyListResponseSerializer
    • AFImageResponseSerializer
    • AFCompoundResponseSerializer

1.3 Additional Functions

  • AFSecurityPolicy
  • AFNetworkReachabilityManager

2. Usage

2.1 AFURLSessionManager

AFURLSession Manager is used to create and manage NSURLSession objects based on a specified NSURLSession Configuration object.

It is subject to <NSURLSession Task Delegate>, <NSURLSession Data Delegate>, <NSURLSession Download Delegate>, and <NSURLSession Delegate>.

2.1.1 Create a Download Task
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];
2.1.2 Create an upload task
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"Success: %@ %@", response, responseObject);
    }
}];
[uploadTask resume];
2.1.3 Create a multi-component upload task with schedule
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
    } error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
              uploadTaskWithStreamedRequest:request
              progress:^(NSProgress * _Nonnull uploadProgress) {
                  // This is not called back on the main queue.
                  // You are responsible for dispatching to the main queue for UI updates
                  dispatch_async(dispatch_get_main_queue(), ^{
                      //Update the progress view
                      [progressView setProgress:uploadProgress.fractionCompleted];
                  });
              }
              completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                  if (error) {
                      NSLog(@"Error: %@", error);
                  } else {
                      NSLog(@"%@ %@", response, responseObject);
                  }
              }];

[uploadTask resume];

Among them, multi-component requests upload multiple files at a time, for example;

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:kURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFormData:[@"11230953" dataUsingEncoding:NSUTF8StringEncoding] name:@"uid"];
        [formData appendPartWithFileData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"myText" ofType:@"txt"]] name:@"file" fileName:@"myText.txt" mimeType:@"text/plain"];
    } error:nil];
2.1.4 Create a Data
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"%@ %@", response, responseObject);
    }
}];
[dataTask resume];

2.2 Request serialization

Request serialization creates requests from URL strings and encodes parameters as query strings or HTTP bodies.

NSString * URLString = @" http://example.com " ;
NSDictionary * parameters = @ { @" foo ": @" bar ",@" baz ": @ [@ 1,@ 2,@ 3 ]};
2.2.1 Query String Parameter Coding
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
2.2.2 URL format parameter coding
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
POST http://example.com/
Content-Type: application/x-www-form-urlencoded

foo=bar&baz[]=1&baz[]=2&baz[]=3
2.2.3 JSON parameter coding
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
POST http://example.com/
Content-Type: application/json

{"foo": "bar", "baz": [1,2,3]}

2.3 Network Connection Management

AFNetwork Reachability Manager is used to monitor the accessibility of domain names and the addresses of WWAN and WiFi network interfaces.

  • Do not use accessibility to decide whether the original request should be sent.
    • You should try sending it.
  • You can use accessibility to decide when to automatically retry requests.
    • Accessibility notification (connection availability) is a good time to initiate retry time, although it may still fail.
  • Network accessibility is a useful tool for determining the cause of possible failure of requests.
    • After a network request fails, tell them that an offline user has a more technical but accurate error than giving them, such as "request timeout".

See also WWDC 2012 Conference 706 "Network Best Practices".

2.3.1 Shared Network Accessibility
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];

[[AFNetworkReachabilityManager sharedManager] startMonitoring];

2.4 Security Policy

AFSecurity Policy is used to evaluate the reliability of servers on secure connections for fixed X.509 certificates and public keys.

Adding a fixed SSL certificate to your application helps prevent man-in-the-middle attacks and other vulnerabilities. It is strongly recommended that applications involving sensitive customer data or financial information should be routed to all communications via HTTPS, configuring and enabling SSL pinning.

2.4.1 Allows invalid SSL certificates
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager ];
manager.securityPolicy.allowInvalidCertificates = YES ; //Not recommended for production

3. Unit testing

AFNetworking includes a set of unit tests in the Tests subdirectory. These tests can be run simply to perform test operations on the platform framework that you want to test.

Translation Notes:

This article is translated from AFNetworking Copyright is officially owned and translation is for learning purposes only.

Keywords: network SSL JSON Mac

Added by DocSeuss on Sun, 16 Jun 2019 00:21:06 +0300