简体   繁体   中英

How to open files imported by UIDocumentPicker?

In my app I picked files by UIDocumentPicker and put file names on a tableView . When clicking on a cell , I want the app open the file. I have no idea how to open the files picked before. Please help.

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

You need to keep a reference to the entire URL, not just the filename.

Add the full url to self.files . Then update your cellForRowAtIndexPath to show just the lastPathComponent of that URL.

Then in didSelectRowAtIndexPath you have the access to the full URL of the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM