使用UIDocumentPickerViewController在Swift中导入文本

Adr*_*ian 7 ios swift xcode6

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

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

这是我到目前为止所得到的:

我已经设置了iCloud功能.作品

委托的具体内容如下:

class MyViewController: UIViewController, UITextViewDelegate, UIDocumentPickerDelegate
Run Code Online (Sandbox Code Playgroud)

我为我要导入的文本类型设置了属性:

@IBOutlet weak var newNoteBody: UITextView!
Run Code Online (Sandbox Code Playgroud)

我的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)

}
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚下面的线应该是什么.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!)
    }
}
Run Code Online (Sandbox Code Playgroud)

Adr*_*ian 18

得到它了!我有两个问题:

1)Apple说你必须在阵列中指定UTI.我调用了documentType a KUTTypeText.它应该是"public.text"数组中的一个.

这是Apple的统一文本标识符(UTI)列表

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

}
Run Code Online (Sandbox Code Playgroud)

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

// 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!)
    }
}
Run Code Online (Sandbox Code Playgroud)