In ios development, AFNetworking is generally used to access network requests. How do you access basic network requests

The following describes the basic network request that may be used at ordinary times, case demo

Get data directly through URL synchronization

This method is usually used to download binary data for images, and is suitable for content that is updated every time

// Start an asynchronous thread that requests network data synchronously
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url = [NSURL URLWithString:@"FM = https://t7.baidu.com/it/u=4162611394, 4275913936 & 193 & f = GIF"];
        NSData *imgData = [NSData dataWithContentsOfURL:url];
        dispatch_async(dispatch_get_main_queue(), ^{
            // Load image information
// self.imageView.image = [UIImage imageWithData:imgData];
        });
    });
Copy the code

Network data is requested via NSURLSession

Initiate a GET request as a block

The system defaults to get requests. You can request data directly through the URL

    // The test URL cannot be accessed
    NSURL *url = [NSURL URLWithString:@"https://www.test.com/login?uid=abc&pwd=123"];
    NSURLSession *session = [NSURLSession sharedSession];
    // Start downloading as a block
    // Note: this request can only be GET
    NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:
    ^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// data: Response body information (expected data)
// Response: Response header information, mainly describes the server side
// error: Indicates an error message, such as
        if(! error) {// The request succeeded. Data is serialized data in JSON format, please use NSJSONSerialization to deserialize processing}}];// Start the task
    [task resume];
Copy the code

Sends a POST request as a block

By default, the system requests get. If you want to change the request to POST, you must set the request to request request. Through request, you can set header data and request type (POST)

NSURL *url = [NSURL URLWithString:@"https://www.test.com/login?uid=abc&pwd=123"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setValue:@"application/json" forHTTPHeaderField:@" content-type "]; [request setValue:@"askdhfkashdkfsidfusdf" forHTTPHeaderField:@"token"]; Request.HTTPMethod = @"POST"; Request. TimeoutInterval = 30.0; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData * _Nullable data, NSURLResponse * _Nullable Response, NSError * _Nullable error) {// data: Response body information (expected data) // Response: response header information, mainly the description of the server side // error: Error message, such as if (! Error) {// the request succeeded, data is serialized in JSON format, please use NSJSONSerialization to deserialize the processing}}]; [task resume];Copy the code

Post requests are made using a proxy protocol

To initiate post request in the way of proxy need to set up the proxy, and implement the proxy protocol of data download (NSURLSessionDelegate, NSURLSessionDataDelegate), mainly is to implement the NSURLSessionDataDelegate related download protocol, AFNetworking uses proxies to implement network requests

- (void)postDataDelegate {
    self.responseData = [NSMutableData data];
    
    NSURL *url = [NSURL URLWithString:@"https://www.test.com/login?uid=abc&pwd=123"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // You can use this method
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"askdhfkashdkfsidfusdf" forHTTPHeaderField:@"token"];
    // The default is GET. The POST request method needs to be set
    request.HTTPMethod = @"POST";
    request.timeoutInterval = 30.0;
    // Use the default session configuration, proxy and proxy callback queues
    NSURLSession *session = [NSURLSession sessionWithConfiguration:
    [NSURLSessionConfiguration defaultSessionConfiguration] 
    delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    NSURLSessionTask *task = [session dataTaskWithRequest:request];
    [task resume];
}
    
    // Set the response mode for data requests
    - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
                                 didReceiveResponse:(NSURLResponse *)response
                                  completionHandler: (void (^)(NSURLSessionResponseDisposition disposition))completionHandler
{
    / * NSURLSessionResponseCancel = 0, the default way to handle it, Cancel NSURLSessionResponseAllow = 1, Receive data from server NSURLSessionResponseBecomeDownload = 2, a * / download request NSURLSessionResponseBecomeStream into a flow
    completionHandler(NSURLSessionResponseAllow);
}

//2. This method is called when data is received from the server. If the data is large, this method may be called several times- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    [self.responseData appendData:data];
}

/ / 3. When the request (download) finish (success | failure) will call the method, if the request fails, the error value- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    if(error == nil)
    {
        // The request succeeded
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:nil];
        NSLog(@"% @",dict);
    }else {
        // The request failed}}Copy the code

Initiate the download of file data by proxy protocol

Download files in the form of proxy, you need to set up agent, and implement the data download of the agency agreement (NSURLSessionDelegate, NSURLSessionDownloadDelegate), Mainly is to realize the NSURLSessionDownloadDelegate related download agreement

// If you want to support breakpoint continuation download, you need to check whether there is a local download file before downloading a URL. If there is, check whether the download is complete. If not, continue downloading
- (void)downloadBlock {
    NSURL *url = [NSURL URLWithString:@"https://pic.ibaotu.com/00/48/71/79a888piCk9g.mp4"];
    // Set the background download session configuration
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"testBackgroundIdentifier"];
    // Allow requests to be routed through cellular routing
    config.allowsCellularAccess = YES;
    config.timeoutIntervalForRequest = 30;
    // Download the url from the block, location, which has a path that can be opened or removed
// [NSURLSession sessionWithConfiguration:config];
// [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// if (! error) {
// // Download success can be played
/ /}
/ /}];
    // Use proxy download
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    // Resumable
// 1. Check whether the file path exists through NSFileManager
// 2. There is no direct download
// NSData *resumeData = [NSData dataWithContentsOfFile:@" address "];
// 3. Continue downloading
// [session downloadTaskWithResumeData:resumeData];
// 4. Enable background tasks for background download to avoid problems during the download process. Disable background tasks after the download is complete
// [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(){}];[session downloadTaskWithURL:url]; } - (void)URLSession:(nonnull NSURLSession *)session downloadTask:(nonnull NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    // Get the percentage of downloads completed
    //float downPro = 1.0 * totalBytesWritten / totalBytesExpectedToWrite;
}

 // Call this method after the download is complete- (void)URLSession:(nonnull NSURLSession *)session downloadTask:(nonnull NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(nonnull NSURL *)location{
// NSLog(@"location == %@",location.path);
    // You can get the address by location, move it, or delete it
}

- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session{
    NSLog(@"All background tasks completed: %@",session.configuration.identifier);
}
Copy the code

Breakpoint continuingly

To download a file in resumable mode, proceed as follows

1. Use NSFileManager to check whether the file path exists

2. There is no direct download and present to get the data file to download, download the background you need to set up NSURLSessionConfiguration configured to download the background (backgroundSessionConfigurationWithIdentifier:)

NSData *resumeData = [NSData dataWithContentsOfFile:@" address "];

3. Continue with the downloaded data

[session downloadTaskWithResumeData:resumeData];

4. Enable background tasks for background download to avoid problems during the download process. Disable background tasks after the download is complete

[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(){}];