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

时间:2021-08-08 05:48:53

We are not allowed to store the files persistent but allow the customer to decide himself if he want to save it in a different app/send it somewhere. Sounds like a job for UIDocumentInteractionController but without the persistence part.

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

Inside of the docs Apple states:

苹果公司的文档内部说:

"[…]you can use a document interaction controller with a file that was synced to your app’s Documents/Shared directory."

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

Is it possible to open a file directly without storing it as a file inside of a UIDocumentInteractionController?

是否可以直接打开文件而不将其作为文件存储在UIDocumentInteractionController中?

We already have the PDF / Image as Data. Is there a way to encode Data to an URL and use that to open a Interaction controller?

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

2 个解决方案

#1


1  

This cannot be done, you can only share local resources.

这不可能,您只能共享本地资源。

What you could do is to save the file in a temp folder and the access it. Below is the code of how you can achieve this. Checkout the comments for description:

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

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)
    }
}

There is also no need to delete the file since it´s in the temporary directory.

也没有必要删除该文件,因为它位于临时目录中。

#2


0  

Try Using,

尝试使用,

    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

开发者文档请参阅本教程

#1


1  

This cannot be done, you can only share local resources.

这不可能,您只能共享本地资源。

What you could do is to save the file in a temp folder and the access it. Below is the code of how you can achieve this. Checkout the comments for description:

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

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)
    }
}

There is also no need to delete the file since it´s in the temporary directory.

也没有必要删除该文件,因为它位于临时目录中。

#2


0  

Try Using,

尝试使用,

    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

开发者文档请参阅本教程