Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using UIDocumentPickerViewController to import text in Swift

Tags:

ios

swift

xcode6

I'm currently taking an iOS development course and as part of my project, I'm tasked with using UIDocumentPickerViewController to import text. Every example I've found is either a) written in Objective-C or b) is for importing UIImage files.

How do I set the delegate method for a text file?

Here's what I've got so far:

I have the iCloud capability set up. Works

The delegate is specified, as follows:

class MyViewController: UIViewController, UITextViewDelegate, UIDocumentPickerDelegate

I have the property set up for the type of text I'm trying to import:

@IBOutlet weak var newNoteBody: UITextView!

I have an IBAction setup as follows:

@IBAction func importItem(sender: UIBarButtonItem) {

    var documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: [kUTTypeText as NSString], inMode: UIDocumentPickerMode.Import)
    documentPicker.delegate = self
    documentPicker.modalPresentationStyle = UIModalPresentationStyle.FullScreen
    self.presentViewController(documentPicker, animated: true, completion: nil)

}

I can't figure out what the line should be below. The documentation on Apple's website isn't clear and every example I've found is in Objective-C or is for images.

// MARK: - UIDocumentPickerDelegate Methods

func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
    if controller.documentPickerMode == UIDocumentPickerMode.Import {
        // What should be the line below?
        self.newNoteBody.text = UITextView(contentsOfFile: url.path!)
    }
}
like image 256
Adrian Avatar asked Feb 21 '15 02:02

Adrian


1 Answers

Got it! I had two problems:

1) Apple says you've gotta specify UTI's in an array. I called the documentType a KUTTypeText. It should be a "public.text" in the array.

Here's Apple's listing of Uniform Text Identifiers (UTIs)

@IBAction func importItem(sender: UIBarButtonItem) {

    var documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: ["public.text"], inMode: UIDocumentPickerMode.Import)
    documentPicker.delegate = self
    documentPicker.modalPresentationStyle = UIModalPresentationStyle.FullScreen
    self.presentViewController(documentPicker, animated: true, completion: nil)

}

The second problem was a syntactic issue on the Delegate, solved with this:

// MARK: - UIDocumentPickerDelegate Methods

func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
    if controller.documentPickerMode == UIDocumentPickerMode.Import {
        // This is what it should be
        self.newNoteBody.text = String(contentsOfFile: url.path!)
    }
}
like image 199
Adrian Avatar answered Nov 09 '22 03:11

Adrian