ios打开文件管理器并展示文本文件内容
时间: 2023-08-02 21:12:38 浏览: 121
iOS 文件查看与展示
3星 · 编辑精心推荐
iOS 中没有一个通用的文件管理器,但是可以使用 UIDocumentPickerViewController 来让用户选择并打开文本文件。以下是一个简单的示例代码:
1. 导入框架:
```
import UIKit
import MobileCoreServices
```
2. 创建一个UIViewController来展示文本内容:
```
class TextFileViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
var url: URL? // 用来获取用户选择的文件的URL
override func viewDidLoad() {
super.viewDidLoad()
if let url = url {
do {
let text = try String(contentsOf: url, encoding: .utf8)
textView.text = text
} catch {
print(error.localizedDescription)
}
}
}
}
```
3. 在需要打开文件的地方,使用 UIDocumentPickerViewController:
```
let documentPicker = UIDocumentPickerViewController(documentTypes: [String(kUTTypePlainText)], in: .import)
documentPicker.delegate = self
present(documentPicker, animated: true, completion: nil)
```
4. 添加 UIDocumentPickerDelegate:
```
extension ViewController: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
if let url = urls.first {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let textFileViewController = storyboard.instantiateViewController(withIdentifier: "TextFileViewController") as? TextFileViewController {
textFileViewController.url = url
navigationController?.pushViewController(textFileViewController, animated: true)
}
}
}
}
```
这样就可以让用户选择并打开文本文件,并在 TextFileViewController 中展示文件内容。
阅读全文