加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:41:18 所属栏目:百科 来源:网络整理
导读:我想构建一个应用程序,它还包括在应用程序中显示和保存PDF的可能性,并在桌面视图中显示它们(作为FileSystem),并在点击一个PDF时打开它们. 这是我的重要问题: 1.如何在我的应用程序上保存PDF本地(例如,如果用户可以输入一个URL),以及它将在哪里保存? 2.保存
我想构建一个应用程序,它还包括在应用程序中显示和保存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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读