Open text in Pages-Swift

In my Swift 2 application, the user creates a line of text through a text field and then shares it with another application. Right now, I can only make a text file as a .txt file that does not provide the Open In Pages feature when opening the system’s sharing dialog box. How can I do this so that the user can open their entered text as a document in Pages?

Should I convert text to .docx or .pages format? And if so, how?

+5
source share
1 answer

The trick is to save the file locally as a .txt file and then open it using the UIDocumentInteractionController . Here is a complete code example:

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

Call openInPages from anywhere in your code (for example, when the user clicks an Export button element):

 openInPages("This will be the body of the new document", title: "SomeTitle") 

this is the result

+4
source

All Articles