使用Swift在iOS中保存PDF文件并显示它们

前端之家收集整理的这篇文章主要介绍了使用Swift在iOS中保存PDF文件并显示它们前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想构建一个应用程序,它还包括在应用程序中显示和保存PDF的可能性,并在桌面视图中显示它们(作为FileSystem),并在点击一个PDF时打开它们.

这是我的重要问题:

1.如何在我的应用程序上保存PDF本地(例如,如果用户可以输入一个URL),以及它将在哪里保存?

2.保存后,如何在表格中显示所有本地存储的文件以打开它们?

由于有几个人要求这个,这相当于 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,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)
})

和斯威夫特的第二个问题的答案:

//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相关文章