Как сохранить и извлечь несколько PDF-файлов из NSUser по умолчанию и загрузить из NSURLSession - PullRequest
0 голосов
/ 03 апреля 2020

Я загружаю несколько файлов PDF с сервера. После завершения загрузки мне нужно сохранить локальные файлы PDF и извлечь их из файлов PDF и отобразить файлы PDF в контроллере взаимодействия UIDocument. Я пишу так. но файлы не отображаются по локальному пути.

-(void)downloadMultiplePDFFiles

{

NSURL *ClientWebServiceURL = [NSURL URLWithString:DOC_VIEWER_URL];

NSString *str_URL = [NSString stringWithFormat:@"%@",ClientWebServiceURL];

NSURL *url = [NSURL URLWithString:str_URL];

//---appending data to url---

NSString *body = [NSString stringWithFormat: @"userid=%@&sessionid=%@&tenantid=%@&deviceid=%@&documentid=%@&documenttype=%@&devicetype=%@&isencrypted=Y",self->userid,self->sessionid,self->tenantid,self->deviceid ,[NSString stringWithFormat:@"%@", documentid],[documenttype stringByReplacingOccurrencesOfString:@" " withString:@""],devicetype];

//---sending request to server---

NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];

[request setHTTPMethod: @"POST"];

[request setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];

self.downloadTask = [self.backgroundSession downloadTaskWithRequest:request];

[self.downloadTask resume];

}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {

if (downloadTask == self.downloadTask) {

double progress = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;

NSLog(@"DownloadTask: %@ progress: %lf", downloadTask, progress);

dispatch_async(dispatch_get_main_queue(), ^{

//  self.progressView.progress = progress;

});

}

}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)downloadURL {

NSFileManager *fileManager = [NSFileManager defaultManager];

NSArray *URLs = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];

NSURL *documentsDirectory = [URLs objectAtIndex:0];

NSURL *originalURL = [[downloadTask originalRequest] URL];

NSURL *destinationURL = [documentsDirectory URLByAppendingPathComponent:[originalURL lastPathComponent]];

NSError *errorCopy;

// For the purposes of testing, remove any esisting file at the destination.

[fileManager removeItemAtURL:destinationURL error:NULL];

BOOL success = [fileManager copyItemAtURL:downloadURL toURL:destinationURL error:&errorCopy];

if (success)

{

dispatch_async(dispatch_get_main_queue(), ^{

//download finished - open the pdf

self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:destinationURL];

// Configure Document Interaction Controller

[self.documentInteractionController setDelegate:self];

// Preview PDF

[self.documentInteractionController presentPreviewAnimated:YES];

//  self.progressView.hidden = YES;

});

} else {

NSLog(@"Error during the copy: %@", [errorCopy localizedDescription]);

}

//    myPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingString:[[DOC_VIEWER_URL componentsSeparatedByString:@"/"]lastObject]];

//NSFileManager *fileManager = [NSFileManager defaultManager];

//[fileManager moveItemAtURL:downloadURL toURL:[NSURL fileURLWithPath:myPath] error:nil];

}

- (UIViewController *) documentInteractionControllerViewControllerForPreview: (UIDocumentInteractionController *) controller{

return self;

}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {

if (error == nil) {

NSLog(@"Task: %@ completed successfully", task);

} else {

NSLog(@"Task: %@ completed with error: %@", task, [error localizedDescription]);

}

double progress = (double)task.countOfBytesReceived / (double)task.countOfBytesExpectedToReceive;

dispatch_async(dispatch_get_main_queue(), ^{

// self.progressView.progress = progress;

});

//self.downloadTask = nil;

}

- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

if (appDelegate.backgroundSessionCompletionHandler) {

void (^completionHandler)() = appDelegate.backgroundSessionCompletionHandler;

appDelegate.backgroundSessionCompletionHandler = nil;

completionHandler();

}

NSLog(@"All tasks are finished");

}

После загрузки файла я получил путь, подобный следующему.

/ Пользователи / Библиотека / Разработчик / CoreSimulator / Devices / 9DEA0DEB-662E -4080-AE2E-F2E3429A5A64 / данные / контейнеры / данные / приложение / BD7BD3D8-E65A-4977-A320-69672A673597 / Documents / ViewDo c .sv c

Проблема в том, что файл pdf недоступен в этом пути.и каждый раз, когда загружается файл pdf download.once, мне нужно загрузить PDF-файл в контроллер взаимодействия UIDocument. Пожалуйста, помогите мне любое тело. Заранее спасибо.

...