ios - 使用临时存储打开文件

标签 ios swift file download

我有一些代码可以下载并打开一个文件:

//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)
}

不过,我不希望将其永久存储 - 只是为了让用户在单击“打开”按钮时能够看到该文件。

有没有办法将文件放在某个地方,比如/temp 文件夹,其中的内容会自动删除,或者,当预览关闭时,我该如何删除文件?

非常感谢!

最佳答案

您的应用程序有一个临时目录,您可以查看File System Basics找到有关您的应用程序可用目录的更多详细信息。您应该管理相关文件的生命周期。

查看此 question用于从此目录中删除文件。

你感兴趣的目录是tmp/

形成文档:

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.

关于ios - 使用临时存储打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34395553/

相关文章:

ios - 如何通过关闭调用点击手势(iOS)

ios - 检索函数数据

java - 访问不同 Java 类中的文件?

ios - Cocoapod podspec引用iOS和OSX项目

ios - 在 Swift 3 中调用 flashScrollIndicators() 时如何更改滚动条的颜色

ios - MvvmCross .dialog 中的 "Failed to create target binding for to"

ios - 如何将数据从 View Controller 传递到选项卡栏 Controller 的第一个选项卡

iphone - NSSet 枚举错误

c - 修改后被其他人覆盖原始文件

oracle - ORA-00439 : feature not enabled: Basic Compression