我想建立一个应用程序,它还可以在应用程序中显示show and save PDFs个,并在tableview中显示它们(作为文件系统),当我点击一个PDF时打开它们.

以下是我的重要问题:

1. How do I save a PDF local on my app ( for example if the user can enter a url) and where exactly will it save it ?

2. When saved, how can I show all the local storaged files within a tableview to open them?

推荐答案

由于有几个人要求这样做,下面是Swift中的第一个答案:

//The URL to Save
let yourURL = NSURL(string: "http://somewebsite.com/somefile.pdf")
//Create a URL request
let urlRequest = NSURLRequest(URL: yourURL!)
//get the data
let theData = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: nil, error: nil)

//Get the local docs directory and append your local filename.
var docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)).last as? NSURL

docURL = docURL?.URLByAppendingPathComponent( "myFileName.pdf")

//Lastly, write your file to the disk.
theData?.writeToURL(docURL!, atomically: true)

此外,由于此代码使用同步网络请求,我强烈建议将其分配到后台队列:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
    //The URL to Save
    let yourURL = NSURL(string: "http://somewebsite.com/somefile.pdf")
    //Create a URL request
    let urlRequest = NSURLRequest(URL: yourURL!)
    //get the data
    let theData = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: nil, error: nil)

    //Get the local docs directory and append your local filename.
    var docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)).last as? NSURL

    docURL = docURL?.URLByAppendingPathComponent( "myFileName.pdf")

    //Lastly, write your file to the disk.
    theData?.writeToURL(docURL!, atomically: true)
})

还有Swift中第二个问题的答案:

//Getting a list of the docs directory
let docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last) as? NSURL

//put the contents in an array.
var contents = (NSFileManager.defaultManager().contentsOfDirectoryAtURL(docURL!, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, error: nil))
//print the file listing to the console
println(contents)



Swift相关问答推荐

运行异步任务串行运行

依赖于@Environment的init@StateObject

Swift-Can无法在AudioKit中找出简单的麦克风效果-文件链

可以';t在标记为@Observable的类上使用属性包装

在SwiftUI中如何预览嵌套的ScrollView,以避免触发可刷新修饰符

RealityKit - 从中心zoom 模型

避免 `(())` 显式指定 Void 类型的枚举关联值

如何将视图添加到多行文本视图的末尾?

确定路径是否相交的有效方法

Swift并发:为什么不在其他后台线程上执行任务

为什么swiftui中的导航视图栏那么大?

AVPlayer 在 iOS 15.4 中寻求 completionHandler 返回 false

如果没有标记,则为 Swift 预处理器

在 UItextfield 的右视图上添加一个按钮,文本不应与按钮重叠

swift : 具有类型和值的枚举常量

是 swift 中另一个日期的同一周、月、年的日期

转换为 swift 3 后,视图控制器中出现奇怪的通用函数

ISO8601DateFormatter 不解析 ISO 日期字符串

带有默认值的 Swift 可选变量赋值(双问号)

在 IOS 项目中放置 .txt 文件并从中读取的位置