使用UIDocumentPickerViewController在Swift中导入文本

时间:2015-02-21 02:19:29

标签: ios swift xcode6

我目前正在参加iOS开发课程,作为项目的一部分,我的任务是使用UIDocumentPickerViewController导入文字。我发现的每个例子都是a)用Objective-C编写或b)用于导入UIImage文件。

如何设置文本文件的委托方法?

以下是我到目前为止所做的事情:

我已设置iCloud功能。的工程

指定委托,如下所示:

class MyViewController: UIViewController, UITextViewDelegate, UIDocumentPickerDelegate

我为我尝试导入的文字类型设置了属性:

@IBOutlet weak var newNoteBody: UITextView!

我的IBAction设置如下:

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

}

我无法弄清楚下面的线应该是什么。 Apple网站上的文档并不清楚,我发现的每个例子都在Objective-C中,或者是用于图像。

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

1 个答案:

答案 0 :(得分:15)

知道了!我有两个问题:

1)Apple说你必须在阵列中指定UTI。我将documentType称为KUTTypeText。它应该是数组中的"public.text"

这是Apple的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)

}

第二个问题是代表的语法问题,解决了这个问题:

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