Document Downloads

PSPDFKit usually works best with PDF documents on the local file system of your device. There are several reasons for using local file system documents (performance, cache control, battery impact, …).

If you have a PDF document that isn’t on the local file system, you can use URLSession to download the PDF and display it using PDFViewController.

Create a URLSession object with the required configurations. Then, use the session to create a download task (URLSessionDownloadTask) with the remote URL of the PDF document. Before resuming the task, make sure you’ve set the session object’s delegate:

Copy
1
2
3
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
let task = session.downloadTask(with: URL(string: "your-remote-url-here")!)
task.resume()
Copy
1
2
3
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"your-remote-url-here"]];
[task resume];

Once the file is downloaded, the urlSession(_:downloadTask:didFinishDownloadingTo:) delegate method is called where the location object is a temporary file URL. Hence it should be moved to a permanent location before opening it with PDFViewController:

Copy
1
2
3
4
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    // The desired saving location of the file is `destinationFileURL`, which `PDFViewController` will later use for loading.
    try! FileManager.default.moveItem(at: location, to: destinationFileURL)
}
Copy
1
2
3
4
5
6
7
8
9
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSError *error;

    //     // The desired saving location of the file is `destinationFileURL`, which `PDFViewController` will later use for loading.
    [[NSFileManager defaultManager] moveItemAtURL:location toURL:destinationFileURL error:&error];
    if (error) {
        NSLog(@"%@", error.localizedDescription);
    }
}

Take a look at DocumentProgressExample.swift in the PSPDFKit Catalog for a complete example.