2016-07-27 33 views
5

在我的Swift 2應用程序中,用戶通過文本字段創建一個文本字符串,然後將其共享到另一個應用程序。現在,我只能將文本共享爲.txt文件,但在打開系統共享對話框時,該文件不提供對Open In Pages的選項。我該如何做到這一點,以便用戶可以選擇在Pages中以文檔形式打開輸入的文本?在頁面中打開文本Swift

我必須將文本轉換爲.docx或.pages格式嗎?如果是這樣,怎麼樣?

回答

4

訣竅是將本地文件保存爲.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") 

this is the result

+0

非常感謝你;我嘗試了你的方法(除了我必須調用'openInPages'就像這樣:'do {0}嘗試openInPages(flowNote.text,title:「從NoteFlow導出,8月1日」) } catch _ { 打印(「無法在Pages中打開」) } '並且在調用該函數時沒有任何事情發生(我在物理iPad空中和iPhone 6模擬器上運行了這個函數)很多非致命錯誤出現在控制檯中,它看起來像XCode必須在Airdrop菜單中打破一系列限制(?)。所以我需要一些幫助! – owlswipe

+0

你可能試圖在應用程序生命週期中過早地調用該方法請參閱更新代碼 – Casey

+0

我不認爲這是它從viewdidload中調用它,就像在你的新代碼中一樣,結果沒有打印錯誤,但也不會導致共享對話框poppi完全沒有問題。 (注意:當調用控制檯時,仍然會彈出錯誤的約束錯誤消息,與您從viewdidload完全一樣。) – owlswipe