如何打开由UIDocumentPicker导入的文件?

时间:2016-05-15 14:38:14

标签: ios swift uitableview uidocumentpickervc

在我的应用中,我选择了UIDocumentPicker的文件并将文件名放在tableView上。点击cell时,我希望应用打开该文件。我不知道如何打开之前选择的文件。请帮忙。

import UIKit

extension ViewController: UIDocumentMenuDelegate {
    func documentMenu(documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
        documentPicker.delegate = self

        self.presentViewController(documentPicker, animated: true, completion: nil)
    }
}

extension ViewController: UIDocumentPickerDelegate {
    func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
        if controller.documentPickerMode == UIDocumentPickerMode.Import {
          dispatch_async(dispatch_get_main_queue()) {

              if let fileName = url.lastPathComponent {

                self.files.append(fileName)

            }

          }            
        }      
    }        
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var files = [AnyObject]()

    @IBOutlet weak var fileTableView: UITableView!
    @IBAction func addDocuments(sender: AnyObject) {
        let importMenu = UIDocumentMenuViewController(documentTypes: ["public.data", "public.text"], inMode: .Import)

        importMenu.delegate = self

        self.presentViewController(importMenu, animated: true, completion: nil)

        let documentPicker = UIDocumentPickerViewController(documentTypes: ["public.data", "public.text"], inMode: .Import)
        documentPicker.delegate = self
        documentPicker.modalPresentationStyle = UIModalPresentationStyle.FullScreen

        self.presentViewController(documentPicker, animated: true, completion: nil)
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    }

1 个答案:

答案 0 :(得分:2)

您需要保留对整个网址的引用,而不仅仅是文件名。

将完整url添加到self.files。然后更新您的cellForRowAtIndexPath以仅显示该网址的lastPathComponent

然后在didSelectRowAtIndexPath中,您可以访问该文件的完整网址。