如何在UIDocumentInteractionController中打开内存文件?

时间:2017-08-24 19:13:18

标签: ios swift uikit uidocumentinteraction

我们不允许存储文件持久性,但允许客户自行决定是否要将其保存在其他应用程序中/将其发送到某处。听起来像UIDocumentInteractionController的工作,但没有持久性部分。

Apple的文档内部说明:

  

" [...]您可以将文档交互控制器与文件一起使用   同步到您应用的文档/共享目录。"

是否可以直接打开文件而不将其存储为UIDocumentInteractionController内的文件?

我们已经将PDF / Image作为数据。有没有办法将数据编码为URL并使用它来打开交互控制器?

2 个答案:

答案 0 :(得分:1)

这不能做,你只能共享本地资源。

您可以做的是将文件保存在临时文件夹中并进行访问。以下是如何实现这一目标的代码。查看评论以获取说明:

import UIKit

class ViewController: UIViewController {
    let sharingController = UIDocumentInteractionController()
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if let pdfURL = Bundle.main.url(forResource: "yourPDF", withExtension: "pdf") {
            do {
                let pdfData = try Data(contentsOf: pdfURL)
                // create a destination url to save your pdf data
                let destURL = FileManager.default.temporaryDirectory.appendingPathComponent("tempFile.pdf")
                // write your pdf data to the destinastion url
                do {
                    try pdfData.write(to: destURL)
                    // share your url using UIDocumentInteractionController
                    shareURL(url: destURL)
                } catch {
                    print(error)
                }
            } catch {
                print(error)
            }
        }
        
    }
    func shareURL(url: URL){
        sharingController.url = url
        sharingController.uti = "public.data, public.content"
        sharingController.name = url.lastPathComponent
        sharingController.presentOptionsMenu(from: view.frame, in: view, animated: true)
    }
}

也无需删除该文件,因为它位于临时目录中。

答案 1 :(得分:0)

尝试使用,

    import UIKit
    import QuickLook
    class YourViewController:UIViewController,QLPreviewControllerDataSource, QLPreviewControllerDelegate {

       func openFile(){

        let objURL = "file URL "
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
        let url = URL(fileURLWithPath: path)
        let theFileName = (objURL as NSString).lastPathComponent
        let filePath = url.appendingPathComponent("\(theFileName)").path
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: filePath) {
            print("FILE AVAILABLE")
            self.pathString = filePath
            let viewPDF = QLPreviewController()
            viewPDF.dataSource = self
            viewPDF.delegate = self
            self.item.previewItemTitle = self.previewFileTitle
            self.item.previewItemURL = URL.init(fileURLWithPath: filePath)
            self.present(viewPDF, animated: true, completion: nil)
        } else {
            print("FILE NOT AVAILABLE")
            previewFileTitle = theFileName
            self.downloadPDF(objURL)
        }


    }

    func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
        return 1
    }

    func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {

        let url = URL(fileURLWithPath: pathString)

        return item as QLPreviewItem
    }

    func previewController(_ controller: QLPreviewController, shouldOpen url: URL, for item: QLPreviewItem) -> Bool {
        return true
    }
    func downloadPDF(_ url:String){
        let requestURL: URL = URL(string: url)!
        let urlRequest: URLRequest = URLRequest(url: requestURL)
        let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
            if let httpResponse = response as? HTTPURLResponse {
                let statusCode = httpResponse.statusCode
                if (statusCode == 200) {
                    print("Downloaded Successfully")
                    let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
                    let sourceUrl = URL(string:url)!
                    //Get the file name and create a destination URL
                    let fileName = sourceUrl.lastPathComponent
                    let destinationURL = documentsDirectoryUrl!.appendingPathComponent(fileName)

                    //Hold this file as an NSData and write it to the new location
                    if let fileData = try? Data(contentsOf: sourceUrl) {
                        try? fileData.write(to: destinationURL, options: [])   // true
                        print(destinationURL.path)
                        self.pathString = destinationURL.path
                        let viewPDF = QLPreviewController()
                        viewPDF.dataSource = self
                        viewPDF.delegate = self
                        self.item.previewItemTitle = self.previewFileTitle
                        self.item.previewItemURL = destinationURL
                        self.present(viewPDF, animated: true, completion: nil)
                    }

                }else{
                }
            }
        }
        task.resume()

    }
}

class PreviewItem: NSObject, QLPreviewItem {
    var previewItemURL: URL?
    var previewItemTitle: String?
}

Developer documentation
See this tutorial