Download NSURLSession (proxy)
Download NSURLSession (proxy)
-(Void) downloadTask2
{
{
NSURLSessionConfiguration * cfg = [nsurlsessionconfigurationdefasessessionconfiguration];
// 1. Get the session object
NSURLSession * session = [NSURLSessionsessionWithConfiguration: includelegate: selfdelegateQueue: [NSOperationQueuemainQueue];
// 2. Create a download task
NSURL * url = [NSURLURLWithString: @ "http: // localhost: 8080/MJServer/resources/test.mp4"];
// NSURLSessionDownloadTask * task = [session downloadTaskWithURL: url completionHandler: ^ (NSURL * location, NSURLResponse * response, NSError * error ){
// NSLog (@ "% @", location );
//}];
NSURLSessionDownloadTask * task = [session downloadTaskWithURL: url];
// 3. Start the task
[Task resume];
// If the completionHandler block is set for the download task, the download proxy method is also implemented and the block is preferentially executed.
}
Note: After downloadtask is downloaded, save the data to the tmp temporary file in the sandbox. Cut the temporary file or copy the Caches folder.
# Pragma mark-NSURLSessionDownloadDelegate
/**
* Called after download
*
* @ Param location: Path of the temporary file (downloaded file)
*/
-(Void) URLSession :( NSURLSession *) session downloadTask :( NSURLSessionDownloadTask *) downloadTask didFinishDownloadingToURL :( NSURL *) location
{
// Location: Path of the temporary file (downloaded file)
NSString * caches = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// Response. suggestedFilename: Recommended file name, which is generally the same as the file name on the server.
NSString * file = [cachesstringByAppendingPathComponent: downloadTask. response. suggestedFilename];
// Cut the temporary file or copy the Caches folder
NSFileManager * mgr = [nsfilemanagerdefamanager];
// AtPath: the file path before cutting
// ToPath: the path of the cut File
[Mgr moveItemAtPath: location. pathtoPath: fileerror: nil];
}
/**
* Called when the download is resumed
*/
-(Void) URLSession :( NSURLSession *) session downloadTask :( NSURLSessionDownloadTask *) downloadTask didResumeAtOffset :( int64_t) fileOffset expectedTotalBytes :( int64_t) expectedTotalBytes
{
}
/**
* Each time a part is downloaded (written), it is called (may be called multiple times)
*
* @ Param bytesWritten what is written in this call
* @ Param totalBytesWritten total length written to the sandbox
* @ Param totalBytesExpectedToWrite the total length of the object
*/
-(Void) URLSession :( NSURLSession *) session downloadTask :( 0000*) downloadTask didWriteData :( int64_t) bytesWritten totalBytesWritten :( int64_t) totalBytesWritten listen :( int64_t)
{
Double progress = (double) totalBytesWritten/totalBytesExpectedToWrite;
NSLog (@ "download progress --- % f", progress );
}