NSURLSession and nsurlsessiontask
Introduction
[NSURLSession sharedSession] obtains the global NSURLSession object. All apps on the iPhone share a global session.
NSURLSessionUploadTask-> NSURLSessionDataTask-> NSURLSessionTask
NSURLSessionDownloadTask-> NSURLSessionTask
Download NSURLSessionDownloadTask, Which is downloaded to the tmp folder by default. After the download is complete, delete the temporary file. So we need to move the file to the Cache before deleting it.
Explanation of NSURLSession 1. NSURLSession Basics
- First Network Request Method
// Create a url nsurl * url = [NSURL URLWithString: @ "http: // 192.168.1.200/login. php? Username = haha & password = 123 "]; // create a request // NSURLRequest * request = [NSURLRequest requestWithURL: url]; // create a Session NSURLSession * session = [NSURLSession sharedSession]; // Create task NSURLSessionDataTask * task = [session dataTaskWithURL: url completionHandler: ^ (NSData * _ Nullable data, NSURLResponse * _ Nullable response, NSError * _ Nullable error) {NSLog (@ "% @", [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]) ;}]; // enable the network task [task resume];
- Second network Request Method
// Create a url nsurl * url = [NSURL URLWithString: @ "http: // 192.168.1.200/login. php? Username = haha & password = 123 "]; // create a request NSURLRequest * request = [NSURLRequest requestWithURL: url]; // create a Session NSURLSession * session = [NSURLSession sharedSession]; // create a task NSURLSessionDataTask * task = [session dataTaskWithRequest: request completionHandler: ^ (NSData * _ Nullable data, NSURLResponse * _ Nullable response, NSError * _ Nullable error) {NSLog (@ "% @", [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]) ;}]; // enable the network task [task resume];
NSURL * url = [NSURL URLWithString: @ "http: // 192.168.1.200/login. php "]; NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; // set the request Method request. HTTPMethod = @ "POST"; // sets the request Body request. HTTPBody = [@ "username = haha & password = 123" dataUsingEncoding: NSUTF8StringEncoding]; [[[NSURLSession sharedSession] dataTaskWithRequest: request completionHandler: ^ (NSData * _ Nullable data, NSURLResponse * _ Nullable response, NSError * _ Nullable error) {NSLog (@ "% @", [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]);}] resume]
NSURL * url = [NSURL URLWithString: [@ "http: // 192.168.1.200/dom0000.mp4" Secure: NSUTF8StringEncoding]; NSURLSession * session = [NSURLSession sharedSession]; NSURLSessionDownloadTask * downloadTask = [session downloadTaskWithURL: url completionHandler: ^ (NSURL * _ Nullable location, NSURLResponse * _ Nullable response, NSError * _ Nullable error) {// location: NSLog (@ "download completed % @", location); // response. NSString * cachesPath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: response. suggestedFilename]; NSLog (@ "cache address % @", cachesPath); // obtain the File Manager NSFileManager * mgr = [NSFileManager defaultManager]; // move the temporary file to the cache directory // [NSURL fileURLWithPath: cachesPath] convert the local path to the URL type // if the address is incorrect, the generated url object is blank [mgr moveItemAtURL: location toURL: [NSURL fileURLWithPath: cachesPath] error: NULL] ;}]; [downloadTask resume];
2. NSURLSession proxy
-(Void) touchesBegan :( NSSet <UITouch *> *) touches withEvent :( UIEvent *) event {// global session // NSURLSession * session = [NSURLSession sharedSession]; // create a custom session // configure NSURLSessionConfiguration // [[NSOperationQueue alloc] init] can also be written as nil NSURL * url = [NSURL URLWithString: @ "http: // 192.168.1.200/login. php? Username = haha & password = 123 "]; NSURLSession * session = [NSURLSession sessionWithConfiguration: [NSURLSessionConfiguration defaultSessionConfiguration] delegate: self delegateQueue: [[NSOperationQueue alloc] init]; NSURLSessionDataTask * task = [session dataTaskWithURL: url]; [task resume];} // receives the server response-(void) URLSession :( NSURLSession *) session dataTask :( NSURLSessionDataTask *) dataTaskdidReceiveResponse :( NSURLResponse *) response completionHandler :( void (^) (NSURLSessionResponseDisposition disposition) completionHandler {NSLog (@ "% s" ,__ FUNCTION __); // allow the server to return the data completionHandler (NSURLSessionResponseAllow);} // receives the data returned by the server, which may be executed multiple times-(void) URLSession :( NSURLSession *) session dataTask :( NSURLSessionDataTask *) dataTask didReceiveData :( NSData *) data {NSLog (@ "% @", [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]);} // request success or failure-(void) URLSession :( NSURLSession *) session task :( NSURLSessionTask *) task didCompleteWithError :( NSError *) error {NSLog (@ "% @", error );}
3. Download large NSURLSession files
# Import "ViewController. h "@ interface ViewController () <NSURLSessionDownloadDelegate> @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSLog (@ "% @", NSSearchPathForDirectoriesInDomains (9, 1, 1);}-(void) touchesBegan :( NSSet <UITouch *> *) touches withEvent :( UIEvent *) event {NSURLSession * session = [NSURLSession sessionWithConfiguration: [NSURLSessionConfiguration defaultSessionConfiguration] delegate: self defined: [NSOperationQueue alloc] init]; optional * task = [session ended: [NSURL URLWithString: [@ "http: // 192.168.1.200/dom=.mp4" stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; [task resume];}/* monitor the data size of temporary file downloads, each time a temporary file is written, the total size of the totalBytesExpectedToWrite file written to bytesWritten is called. */-(void) URLSession :( NSURLSession *) session downloadTask :( NSURLSessionDownloadTask *) downloadTask didWriteData :( int64_t) bytesWritten totalBytesWritten :( int64_t) percent :( int64_t) percent {// print the download percentage NSLog (@ "% f ", totalBytesWritten * 1.0/totalBytesExpectedToWrite);} // download completed-(void) URLSession :( NSURLSession *) session downloadTask :( NSURLSessionDownloadTask *) Resume :( NSURL *) location {NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: downloadTask. response. handler]; NSFileManager * mgr = [NSFileManager defaultManager]; [mgr moveItemAtURL: location toURL: [NSURL fileURLWithPath: cachesPath] error: NULL];}-(void) URLSession :( NSURLSession *) session task :( NSURLSessionTask *) task didCompleteWithError :( NSError *) error {NSLog (@ "% @", error );}
4. NSURLSession resumable Data Transfer
# Import "ViewController. h "@ interface ViewController () <NSURLSessionDownloadDelegate> @ property (nonatomic, strong) NSURLSessionDownloadTask * task; @ property (nonatomic, strong) NSData * resumeData; @ property (nonatomic, strong) NSURLSession * session; @ end @ implementation ViewController // response method of the start button in the storyboard-(IBAction) start :( id) sender {NSURLSession * session = [NSURLSession sessionWithConfiguration: [NSURLSessionConfiguration defaultSessionConfiguration] delegate: self delegateQueue: [[NSOperationQueue alloc] init]; self. session = session; self. task = [session downloadTaskWithURL: [NSURL URLWithString: [@ "http: // 192.168.1.68/ .mp3 .mp3" stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; [self. task resume];} // response method of the pause button in the storyboard-(IBAction) pause :( id) sender {// pause means to suspend the task [self. task cancelByProducingResumeData: ^ (NSData * resumeData) {// Save the downloaded data self. resumeData = resumeData ;}] ;}// response method of the continue button-(IBAction) resume :( id) sender {// you can use ResumeData to create a Task self. task = [self. session downloadTaskWithResumeData: self. resumeData]; // enable the [self. task resume];}-(void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSLog (@ "% @", NSSearchPathForDirectoriesInDomains (9, 1, 1);}/* monitors the size of data downloaded from the temporary file. Each time a temporary file is written, it will call the total size of the bytes file written to bytesWritten at a time */-(void) URLSession :( NSURLSession *) session downloadTask (Bytes *) downloadTask didWriteData :( int64_t) bytesWritten totalBytesWritten :( int64_t) percent :( int64_t) percent {// print the download percentage NSLog (@ "% f", totalBytesWritten * 1.0/percent);} // download completed-(void) URLSession :( NSURLSession *) session downloadTask :( NSURLSessionDownloadTask *) Restart :( NSURL *) location {NSString * cachesPath = [[callback (NSCachesDirectory, NSUserDomainMask, YES) lastObject] resume: downloadTask. response. handler]; NSFileManager * mgr = [NSFileManager defaultManager]; [mgr moveItemAtURL: location toURL: [NSURL fileURLWithPath: cachesPath] error: NULL];}-(void) URLSession :( NSURLSession *) session task :( NSURLSessionTask *) task didCompleteWithError :( NSError *) error {NSLog (@ "% @", error );}