Ben
Ben

Reputation: 4867

Open file using temporary storage

I have some code to download and open a file:

//Get documents directory URL
let documentsDirectoryUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first

let sourceUrl = NSURL(string:"https://download.com/file.pdf")!

//Get the file name and create a destination URL
let fileName = sourceUrl.lastPathComponent!
let destinationURL = documentsDirectoryUrl!.URLByAppendingPathComponent(fileName)

//Hold this file as an NSData and write it to the new location
if let fileData = NSData(contentsOfURL: sourceUrl) {
    fileData.writeToURL(destinationURL, atomically: false)   // true

    let viewer = UIDocumentInteractionController(URL:destinationURL)
    viewer.delegate = self
    viewer.presentPreviewAnimated(true)
}

I don't want this to be stored permanently however - just to allow users to see the file when they click on the 'open' button.

Is there a way to put the file somewhere like a /temp folder where stuff is deleted automatically, or alternatively, how would I remove the file when the preview is closed?

Many thanks!

Upvotes: 0

Views: 1306

Answers (1)

Peter Hornsby
Peter Hornsby

Reputation: 4256

There is a temp directory for your app, you can review File System Basics to find more detail on the directories available to your app. You are expected to manage the life cycle of the files in question.

See this question for deleting a file from this directory.

The directory your interested in is tmp/

Form the documentation:

Use this directory to write temporary files that do not need to persist between launches of your app. Your app should remove files from this directory when they are no longer needed; however, the system may purge this directory when your app is not running. The contents of this directory are not backed up by iTunes.

Upvotes: 1

Related Questions