Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open text in Pages—Swift

Tags:

ios

swift

In my Swift 2 app, a user creates a string of text via a text field then shares it to another app. Right now, I can only make the text share as a .txt file, which doesn't provide the option to Open In Pages when I open the system share dialog. How can I make it so that the user has an option to open their inputted text as a document in Pages?

Must I convert the text to a .docx or .pages format? And if so, how?

like image 968
owlswipe Avatar asked Jul 27 '16 22:07

owlswipe


1 Answers

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

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 (like when the user presses an Export bar button item):

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

this is the result

like image 181
Casey Avatar answered Oct 18 '22 18:10

Casey