newdeveloper newdeveloper - 2 years ago 622
Swift Question

How to open files imported by UIDocumentPicker?

In my app I picked files by

and put file names on a
. When clicking on a
, 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 {




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

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

importMenu.delegate = self

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

let documentPicker = UIDocumentPickerViewController(documentTypes: ["", "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) {

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download