在我的Swift 2应用程序中,用户通过文本字段创建一串文本,然后将其共享给另一个应用程序。现在,我只能将文本共享作为.txt文件,当我打开系统共享对话框时,它不向Open In Pages
提供选项。我如何才能使用户可以选择在Pages中将其输入的文本作为文档打开?
我必须将文本转换为.docx或.pages格式吗?如果是这样,怎么样?
答案 0 :(得分:5)
诀窍是将文件本地保存为.txt文件,然后使用UIDocumentInteractionController
打开它。以下是完整的示例代码:
import UIKit
class ViewController: UIViewController, UIDocumentInteractionControllerDelegate {
var interactionController: UIDocumentInteractionController?
func openInPages(body: String, title: String) throws {
// create a file path in a temporary directory
let fileName = "\(title).txt"
let filePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(fileName)
// save the body to the file
try body.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding)
// for iPad to work the sheet must be presented from a bar item, retrieve it here as below or create an outlet of the Export bar button item.
let barButtonItem = navigationItem.leftBarButtonItem!
// present Open In menu
interactionController = UIDocumentInteractionController(URL: NSURL(fileURLWithPath: filePath))
interactionController?.presentOptionsMenuFromBarButtonItem(barButtonItem, animated: true)
}
}
从代码中的任意位置拨打openInPages
(例如,当用户按下Export
栏按钮项时):
openInPages("This will be the body of the new document", title: "SomeTitle")