NSURLSessionDownloadTask *downloadTask = [ourSession downloadTaskWithRequest:simpleNSURLRequest];
[NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
-(NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler
[self.resumableTask cancelByProducingResumeData:^(NSData *resumeData) { partialDownload = resumeData; self.resumableTask = nil; }]; // if(partialDownload) { self.resumableTask = [inProcessSession downloadTaskWithResumeData:partialDownload]; } else { ... } [self.resumableTask resume];
NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig]; NSURL* downloadTaskURL = [NSURL URLWithString:@"http://upload.wikimedia.org/wikipedia/commons/1/14/Proton_Zvezda_crop.jpg"]; [[session downloadTaskWithURL: downloadTaskURL completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) { NSFileManager *fileManager = [NSFileManager defaultManager]; NSArray *urls = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]; NSURL *documentsDirectory = [urls objectAtIndex:0]; NSURL *originalUrl = [NSURL URLWithString:[downloadTaskURL lastPathComponent]]; NSURL *destinationUrl = [documentsDirectory URLByAppendingPathComponent:[originalUrl lastPathComponent]]; NSError *fileManagerError; [fileManager removeItemAtURL:destinationUrl error:NULL]; // ! [fileManager copyItemAtURL:location toURL:destinationUrl error:&fileManagerError]; }] resume];
NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil]; NSURL* downloadTaskURL = [NSURL URLWithString:@"http://upload.wikimedia.org/wikipedia/commons/1/14/Proton_Zvezda_crop.jpg"]; [[session downloadTaskWithURL:downloadTaskURL] resume]; // - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { // }
sessionConfig.HTTPMaximumConnectionsPerHost = 5;
- (void) methodForNSURLSession{ NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; _tasksArray = [[NSMutableArray alloc] init]; sessionConfig.HTTPMaximumConnectionsPerHost = 5; sessionConfig.timeoutIntervalForResource = 0; sessionConfig.timeoutIntervalForRequest = 0; NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil]; // download tasks // [self createDataTasksWithSession:session]; // data tasks [self createDownloadTasksWithSession:session]; } - (void) createDownloadTasksWithSession:(NSURLSession *)session{ for (int i = 0; i < 10; i++) { NSURLSessionDownloadTask *sessionDownloadTask = [session downloadTaskWithURL: [NSURL URLWithString:@"https://discussions.apple.com/servlet/JiveServlet/showImage/2-20930244-204399/iPhone%2B5%2BProblem2.jpg"]]; [_tasksArray addObject:sessionDownloadTask]; [sessionDownloadTask addObserver:self forKeyPath:@"countOfBytesReceived" options:NSKeyValueObservingOptionOld context:nil]; [sessionDownloadTask resume]; } } - (void) createDataTasksWithSession:(NSURLSession *)session{ for (int i = 0; i < 10; i++) { NSURLSessionDataTask *sessionDataTask = [session dataTaskWithURL: [NSURL URLWithString:@"https://discussions.apple.com/servlet/JiveServlet/showImage/2-20930244-204399/iPhone%2B5%2BProblem2.jpg"]]; [_tasksArray addObject:sessionDataTask]; [sessionDataTask addObserver:self forKeyPath:@"countOfBytesReceived" options:NSKeyValueObservingOptionOld context:nil]; [sessionDataTask resume]; } } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ if([[change objectForKey:@"old"] integerValue] == 0){ NSLog(@"task %d: started", [_tasksArray indexOfObject: object]); } } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{ NSLog(@"task %d: finished!", [_tasksArray indexOfObject:task]); }
sessionConfig.timeoutIntervalForResource = 0; sessionConfig.timeoutIntervalForRequest = 0;
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { double progress = (double)totalBytesWritten / (double)totalBytesExpectedToWrite; NSLog(@"download: %@ progress: %f", downloadTask, progress); dispatch_async(dispatch_get_main_queue(), ^{ self.progressView.progress = progress; }); }
*) session downloadTask: (NSURLSessionDownloadTask *) downloadTask didWriteData: (int64_t) bytesWritten totalBytesWritten: (int64_t) totalBytesWritten totalBytesExpectedToWrite: (int64_t) totalBytesExpectedToWrite - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { double progress = (double)totalBytesWritten / (double)totalBytesExpectedToWrite; NSLog(@"download: %@ progress: %f", downloadTask, progress); dispatch_async(dispatch_get_main_queue(), ^{ self.progressView.progress = progress; }); }
- (NSURLSession *)backgroundSession{ static NSURLSession *session = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ // , NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.dev.BackgroundDownloadTest.BackgroundSession"]; [config setAllowsCellularAccess:YES]; session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; }); return session; }
self.downloadTask = [[self backgroundSession] downloadTaskWithURL:[NSURL URLWithString:@"https://discussions.apple.com/servlet/JiveServlet/showImage/2-20930244-204399/iPhone%2B5%2BProblem2.jpg"]]; [self.downloadTask resume];
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { // save image // //... // set image if (success) { dispatch_async(dispatch_get_main_queue(), ^{ self.imageView.image = [UIImage imageWithContentsOfFile:[destinationPath path]]; [self.progressView setHidden:YES]; }); } }
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { if (error) { NSLog(@"error: %@ - %@", task, error); } else { NSLog(@"success: %@", task); } self.downloadTask = nil; // , [self callCompletionHandlerIfFinished]; }
- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler { // , UILocalNotification* locNot = [[UILocalNotification alloc] init]; locNot.fireDate = [NSDate dateWithTimeIntervalSinceNow:1]; locNot.alertBody = [NSString stringWithFormat:@"still alive!"]; locNot.timeZone = [NSTimeZone defaultTimeZone]; [[UIApplication sharedApplication] scheduleLocalNotification:locNot]; // - , , // UI . // self.backgroundSessionCompletionHandler = completionHandler; }
- (void)viewDidLoad { [super viewDidLoad]; [self backgroundSession]; }
- (void)callCompletionHandlerIfFinished { NSLog(@"call completion handler"); [[self backgroundSession] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { NSUInteger count = [dataTasks count] + [uploadTasks count] + [downloadTasks count]; if (count == 0) { // // // UI NSLog(@"all tasks ended"); AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; if (appDelegate.backgroundSessionCompletionHandler == nil) return; void (^comletionHandler)() = appDelegate.backgroundSessionCompletionHandler; appDelegate.backgroundSessionCompletionHandler = nil; comletionHandler(); } }]; }
Warning: Application delegate received call to - application:handleEventsForBackgroundURLSession:completionHandler: but the completion handler was never called.
Source: https://habr.com/ru/post/209736/
All Articles