我想构建一个应用程序,其中还包括在应用程序内部 显示和保存PDF 并在表格视图中显示它们(作为文件系统)并在我点击一个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, 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)