1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
   | NSURL *url = [NSURL URLWithString:@"https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/ObjC_classic/FoundationObjC.pdf"];
  // 1.创建 NSURLSessionConfiguration NSURLSessionConfiguration *backgroundConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier: @"com.myapp.networking.background"];
  // 2.创建 NSURLSession NSOperationQueue *operationQueue = [NSOperationQueue mainQueue];
  NSURLSession *backgroundSession = [NSURLSession sessionWithConfiguration:backgroundConfiguration delegate:self delegateQueue:operationQueue];
  // 3.创建 NSURLSessionDownloadTask NSURLSessionDownloadTask *downloadTask = [backgroundSession downloadTaskWithURL:url]; [downloadTask resume];
  # prama mark - Delegate - (void)URLSession:(NSURLSession *)session       downloadTask:(NSURLSessionDownloadTask *)downloadTask       didWriteData:(int64_t)bytesWritten  totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {     NSLog(@"Session %@ download task %@ wrote an additional %lld bytes (total %lld bytes) out of an expected %lld bytes.n", session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); }   - (void)URLSession:(NSURLSession *)session       downloadTask:(NSURLSessionDownloadTask *)downloadTask  didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes {     NSLog(@"Session %@ download task %@ resumed at offset %lld bytes out of an expected %lld bytes.n", session, downloadTask, fileOffset, expectedTotalBytes); }   - (void)URLSession:(NSURLSession *)session       downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {     NSLog(@"Session %@ download task %@ finished downloading to URL %@n", session, downloadTask, location);       // Perform the completion handler for the current session     self.completionHandlers[session.configuration.identifier]();      // Open the downloaded file for reading     NSError *readError = nil;     NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingFromURL:location error:readError];     // ...      // Move the file to a new URL     NSFileManager *fileManager = [NSFileManager defaultManager];     NSURL *cacheDirectory = [[fileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] firstObject];     NSError *moveError = nil;     if ([fileManager moveItemAtURL:location toURL:cacheDirectory error:moveError]) {         // ...     } }
   |