Document Downloads

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

If you have a PDF document that is not on the local filesystem, you can use URLSession to download the PDF and display it using PSPDFViewController.

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 have 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 delegate method URLSession:downloadTask:didFinishDownloadingToURL: is called where the location object is a temporary file URL. Hence it should be moved to a permanent location before opening it with PSPDFViewController.

Copy
1
2
3
4
5
6
7
8
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    do {
        // destinationFileURL is the desired location of the file to save which shall be used by PSPDFViewController.
        try FileManager.default.moveItem(at: location, to: destinationFileURL)
    } catch {
        print(error)
    }
}
Copy
1
2
3
4
5
6
7
8
9
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSError *error;

    // destinationFileURL is the desired location of the file to save which shall be used by PSPDFViewController.
    [[NSFileManager defaultManager] moveItemAtURL:location toURL:destinationFileURL error:&error];
    if (error) {
        NSLog(@"%@", error.localizedDescription);
    }
}

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