开发 Document-Based App
iOS 11 增加了 Files 应用,Xcode 中也增加了 Document-Based App 模版。可以快速创建和系统 File 应用 UI 一致的 Document-Based App。
代码编写
用模版创建新的工程后,Xcode 已经帮你创建了 DocumentBrowserViewController,DocumentViewController,Document 三个类。部分代码如下:
// DocumentBrowserViewController.swift
func documentBrowser(_ controller: UIDocumentBrowserViewController, didPickDocumentsAt documentURLs: [URL]) {
guard let sourceURL = documentURLs.first else { return }
presentDocument(at: sourceURL)
}
func presentDocument(at documentURL: URL) {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let documentViewController = storyBoard.instantiateViewController(withIdentifier: "DocumentViewController") as! DocumentViewController
documentViewController.document = Document(fileURL: documentURL)
present(documentViewController, animated: true, completion: nil)
}
这段代码处理点击文件后的操作。presentDocument 方法创建了一个 DocumentViewController 实例,DocumentViewController 的 viewWillAppear 方法会调用 Document.open 方法,从 URL 中异步读取数据。系统会自动处理一些可能发生的意外情况,并在打开文件成功或失败时回调传入的 completionHandler。
设置支持的文件类型
为了告诉系统我们的 App 支持打开哪种文件,还需要在 Info.plist 文件或 Project 的 Info 标签页设置 App 支持的文档类型。比如这里需要支持打开 Guitar Pro 5 文件,扩展名为 gp5。需要作以下设置:
- 在 Document Types 下点击加号“+”,新建一个 Document Type。Name 输入 Guitar Pro 5,Types 输入 com.guitarpro.gp5
- 设置 Additional document type Properties 的 CFBundleTypeRole 和 LSHandlerRank 属性
- 在 Exported UTIs 下点击加号“+”,新建一个 Exported UTI。Description 输入 Guitar Pro 5,Identifier 为 com.guitarpro.gp5,Conforms To 输入 public.content, public.data
- 在 Additional exported UTI properties 中新建 Dictionary 名为 UTTypeTagSpecification
- 在创建的 Dictionary 下新建 public.mime-type 设置为 public.content,新建 public.filename-extension 设置为 gp5
作出以上设置后,App 已经关联了带有 gp5 后缀的文件。在此 App 或 iOS 的 Files 应用中点击 gp5 格式的文件时,就会调用 didPickDocumentsAt 方法打开文件了。