Good articles to my personal technology blog: https://cainluo.github.io/14981091675323.html


Continue to watch knowledge

Continue with the previous article, if you have not seen the friends can go to see play iOS development: NSURLSession explained (a), otherwise it will not know the beginning and end, so next to continue to talk.


Start network request

As mentioned earlier, NSURLSession itself does not make network requests, so what if we want to use GET or POST requests? Let’s get straight to the code:

GET request:

    // Get the shared singleton Session object
    NSURLSession *urlSession = [NSURLSession sharedSession];
    
    // The requested URL is not compatible with HTTP. If you want to be compatible with HTTP requests, you can configure it in the project
    NSURL *url = [NSURL URLWithString:@"https://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E5%9B%BE%E7%89%87"];
    
    // Create the NSURLSessionDataTask object with the URL above and print the Data in completionHandler:
    NSURLSessionDataTask *dataTask = [urlSession dataTaskWithURL:url
                                               completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                                   
                                                   NSLog(@" Requested data is: %@"The [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
                                               }];
    
    // Start the task
    [dataTask resume];
Copy the code

POST request:

    // Get the shared singleton Session object
    NSURLSession *urlSession = [NSURLSession sharedSession];
    
    // Create an NSURL object
    NSURL *url = [NSURL URLWithString:@"https://image.baidu.com/search/index?"];
    
    // Create an NSMutableURLRequest object and set the HTTPMethod request and HTTPBody request content.
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    
    urlRequest.HTTPMethod = @"POST";
    urlRequest.HTTPBody   = [@"tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E5%9B%BE%E7%89%87" dataUsingEncoding:NSUTF8StringEncoding];
    
    // Create an NSURLSessionDataTask from the NSURLRequest object and NSLog the requested data in the completionHandler: callback method.
    NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:urlRequest
                                                   completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
                                                       NSLog(@" Requested data is: %@"The [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
                                                   }];
    
    // Start the task
    [dataTask resume];
Copy the code

Upload a file

Now let’s look at the methods of uploading files. There are also several methods of uploading files. Let’s look at them one by one:

Upload according to the specified local file address:

    // Create an NSURLRequest object with an explicit upload address, otherwise where would you upload it to?
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@" Upload address"]].// NSURL for local files
    NSURL *fileURL = [NSURL URLWithString:@" Local file address"];
    
    // Create an NSURLSessionUploadTask using the NSURLRequest object, configure the URL for File, and check in the completionHandler: callback to see if we uploaded successfully.
    NSURLSessionUploadTask *uploadTask = [[NSURLSession sharedSession] uploadTaskWithRequest:urlRequest
                                                                                    fromFile:fileURL
                                                                           completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                                                               
                                                                               NSLog(@" Upload information: %@"[NSJSONSerialization JSONObjectWithData:data
                                                                                                                                  options:kNilOptions
                                                                                                                                    error:nil]);
                                               }];
    
    // Start the task
    [uploadTask resume];
Copy the code

Upload according to the specified NSData object:

    // Create an NSURLRequest object
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@" Upload address"]].// Create an NSData object, which I won't write in detail here because I don't have a server to upload to
    NSData *fileData = [NSData data];
    
    // Create an NSURLSessionUploadTask from the NSURLRequest object, configure the NSData object, and check in the completionHandler: callback to see if we uploaded successfully.
    NSURLSessionUploadTask *uploadTask = [[NSURLSession sharedSession] uploadTaskWithRequest:urlRequest
                                                                                    fromData:fileData
                                                                           completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                                                               
                                                                               NSLog(@" Upload information: %@"[NSJSONSerialization JSONObjectWithData:data
                                                                                                                                  options:kNilOptions
                                                                                                                                    error:nil]);
                                                                    }];
                                                                    
    // Execute the task
    [uploadTask resume];
Copy the code

Upload in the way of data stream, veteran drivers say this way is quite good, because the advantage is the size of unlimited.

    // Initialize an upload address
    NSString *urlString = @" Upload address";
    
    // If special characters appear in the uploaded URL, we need to do special processing here
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    NSURL *url = [NSURL URLWithString:urlString];
    
    // Create an NSMutableURLRequest object
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    
    // Set the network request mode to POST
    urlRequest.HTTPMethod = @"POST";
    
    // Create an NSData object and set the address to upload the file
    NSData *fileData = [NSData dataWithContentsOfFile:@" File path"];
    
    // NSURLSessionUploadTask is created with the specified URLRequest and FildData, and the completionHandler: method is used to check whether the task was successfully uploaded
    NSURLSessionUploadTask *uploadTask = [[NSURLSession sharedSession] uploadTaskWithRequest:urlRequest
                                                                                    fromData:fileData
                                                                           completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
                                                                               if (error) {
                                                                                   
                                                                                   NSLog(Error uploading: %@, error);
                                                                                   
                                                                                   return;
                                                                               }
                                                                               
                                                                               NSLog(@" Upload you successfully: %@"The [[NSString alloc] initWithData:data
                                                                                                                       encoding:NSUTF8StringEncoding]);
                                                                           }];
    
    // Execute the task
    [uploadTask resume];
Copy the code

To upload in form mode, we need to define two methods:

// The path of the incoming file, the name of the file, and the name of the uploaded file that needs to be changed
- (NSData *)getHTTPBodyWithFilePath:(NSString *)filePath
                           fileName:(NSString *)fileName
                           restName:(NSString *)restName {
    
    NSMutableData *data = [NSMutableData data];
    
    NSURLResponse *response = [self getLocalFileResponse:filePath];
    
    // File type: MIMEType File size: expectedContentLength Filename: suggestedFilename
    NSString *fileType = response.MIMEType;
    
    // If no uploaded file name is passed in, use the local file name!
    if (restName == nil) {
        restName = response.suggestedFilename;
    }
    
    // Form splicing
    NSMutableString *headerString =[NSMutableString string];
    
    [headerString appendFormat:@"--%@\r\n".@"boundary"];
    
    Filename: indicates the filename of the upload file
    [headerString appendFormat:@"Content-Disposition: form-data; name=%@; filename=%@\r\n", fileName, restName];
    [headerString appendFormat:@"Content-Type: %@\r\n\r\n",fileType];
    
    [data appendData:[headerString dataUsingEncoding:NSUTF8StringEncoding]].// File contents
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    
    [data appendData:fileData];
    
    NSMutableString *footerStrM = [NSMutableString stringWithFormat:@"\r\n--%@--\r\n".@"boundary"];
    
    [data appendData:[footerStrM  dataUsingEncoding:NSUTF8StringEncoding]].NSLog(@"dataStr=%@"The [[NSString alloc] initWithData:data
                                              encoding:NSUTF8StringEncoding]);
    
    return data;
}

/// Get the response, mainly the file type and filename
- (NSURLResponse *)getLocalFileResponse:(NSString *)urlString {
    
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    // Local file request
    NSURL *url = [NSURL fileURLWithPath:urlString];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    __block NSURLResponse *localResponse = nil;
    
    // Use the semaphore to implement the NSURLSession synchronization request
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [[[NSURLSession sharedSession] dataTaskWithRequest:request
                                     completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                         
                                         localResponse = response;
                                         
                                         dispatch_semaphore_signal(semaphore);
                                         
                                     }] resume];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return  localResponse;
}
Copy the code

Now let’s join the form and upload the file:

    // Initialize an upload address
    NSString *urlString = @" Upload address";
    
    // If special characters appear in the uploaded URL, we need to do special processing here
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    NSURL *url = [NSURL URLWithString:urlString];
    
    // Create an NSMutableURLRequest object
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    
    // Set the network request mode to POST
    urlRequest.HTTPMethod = @"POST";
    
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@".@"boundary"];
    
    [urlRequest setValue:contentType
      forHTTPHeaderField:@"Content-Type"];
    
    // Create an NSData object and set the address to upload the file
    NSData *fileData = [self getHTTPBodyWithFilePath:@"/Users/lifengfeng/Desktop/test.jpg"
                                            fileName:@"file"
                                            restName:@"newName.png"];
    
    urlRequest.HTTPBody = fileData;
    
    [urlRequest setValue:[NSString stringWithFormat:@"%lu", fileData.length]
      forHTTPHeaderField:@"Content-Length"];
    
    // Create NSURLSessionUploadTask from the specified URLRequest, and check whether the task has been successfully uploaded in the completionHandler: method. So FileData here can be ignored
    NSURLSessionUploadTask *uploadTask = [[NSURLSession sharedSession] uploadTaskWithRequest:urlRequest
                                                                                    fromData:nil
                                                                           completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
                                                                               if (error) {
                                                                                   
                                                                                   NSLog(Error uploading: %@, error);
                                                                                   
                                                                                   return;
                                                                               }
                                                                               
                                                                               NSLog(@" Upload you successfully: %@"The [[NSString alloc] initWithData:data
                                                                                                                       encoding:NSUTF8StringEncoding]);
                                                                           }];
    
    // Execute the task
    [uploadTask resume];
Copy the code

The download file

NSURLSessionDownloadTask NSURLSessionDownloadTask NSURLSessionDownloadTask

    // Create a file download address
    NSString *urlString = @" File download address";
    
    // Handle special characters
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSURL *url = [NSURL URLWithString:urlString];
    
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    NSURLSession *urlSession = [NSURLSession sharedSession];
    
    NSURLSessionDownloadTask *downloadTask = [urlSession downloadTaskWithRequest:urlRequest
                                                               completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                                                   
                                                                   if(error) {
                                                                       
                                                                       NSLog(@"download error:%@",error);
                                                                       
                                                                       return;
                                                                   }
                                                                   
                                                                   //location: the location where the file is stored after the download task is completed.
                                                                   // It will only be saved temporarily, so you need to save it
                                                                   
                                                                   NSLog(@"location:%@", location.path);
                                                                   
                                                                   // If you are using an emulator, you can set the save path to the Mac desktop for convenience
                                                                   // NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                                                                   
                                                                   NSString *filePath = @" File storage address";
                                                                   
                                                                   NSError *fileError;
                                                                   
                                                                   [[NSFileManager defaultManager] copyItemAtPath:location.path
                                                                                                           toPath:filePath
                                                                                                            error:&fileError];
                                                                   
                                                                   if(fileError){
                                                                       
                                                                       NSLog(@"file save error: %@",fileError);
                                                                   } else {
                                                                       
                                                                       NSLog(@"file save success"); }}];// Start downloading
    [downloadTask resume];
Copy the code

NSURLSessionStreamTask: NSURLSessionStreamTask: NSURLSessionStreamTask


Transfer Security of APP (ATS)

Since iOS 9 and Mac OS 10.11, Apple dad has wanted to switch all web requests to HTTPS(RFC 2818), but since it’s certainly not possible to switch all at once, there’s a security feature called ATS.

In the new project, we will send a normal HTTP request, this is the ATS to do the ghost, we need to set up in the project, detailed how to set up to baidu.

For more Information, check out NSAppTransportSecurity in the Information Property List Key Reference in Apple’s official documentation.


conclusion

NSURLSessionStreamTask NSURLSessionStreamTask NSURLSessionStreamTask NSURLSessionStreamTask

Similarly, there is still no project this time, so let’s copy the code ourselves.


The last