2015-04-01 26 views
3

我創建了一個文件,我想通過UIDOcumentInteractionController分享它UIDocumentInteractionController()迅速

我如何獲得從那裏我救了我的文件documentsPath和目標路徑的URL不確定

 let someText = NSString(string: "Test") 
     let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String 

     let destinationPath = documentsPath.stringByAppendingPathComponent("Data.txt") 
     var error:NSError? 

     let written = someText.writeToFile(destinationPath, 
      atomically: true, 
      encoding: NSUTF8StringEncoding, 
      error: &error) 

     if written{ 
      println("Successfully stored the file at path \(destinationPath)") 

    let dic = UIDocumentInteractionController() 

    self.dic.URL = url 
      let v = sender as UIView 
      let ok = self.dic.presentOpenInMenuFromRect(
       v.bounds, inView: v, animated: true) 

回答

7

將您的代碼修改爲以下內容

import UIKit 

class ViewController: UIViewController { 
    var docController:UIDocumentInteractionController! 

    override func viewDidLoad() { 
     let someText = NSString(string: "Test") 
     if let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as? String { 

     let destinationPath = documentsPath.stringByAppendingPathComponent("Data.txt") 
     var error:NSError? 

     let written = someText.writeToFile(destinationPath, 
      atomically: true, 
      encoding: NSUTF8StringEncoding, 
      error: &error) 

     if written{ 
      println("Successfully stored the file at path \(destinationPath)") 
      } 
     if let url = NSURL(fileURLWithPath: destinationPath) { 
      docController = UIDocumentInteractionController(URL: url) 
     } 
     } 
    } 

    @IBAction func sendFile(sender:AnyObject) { 
    docController.presentOptionsMenuFromRect(sender.frame, inView:self.view, animated:true) 
    } 

} 

現在將IBAction連接到故事板中的按鈕。下一頁:左側邊欄中

  1. 點擊藍色項目圖標,然後選擇 信息從橫向菜單。
  2. 擴大文檔類型並在名稱字段中輸入「TXT」和 「public.data,public.content」在類型
  3. 現在擴大出口尿路感染,進入「TXT」在標識符字段中和個符合 「public.data,public.content」 的說明 字段, 「kUTTypeText」 到外地

讓一切看起來是這樣的:

enter image description here

您現在可以生成並運行應用程序來測試。