2015-04-01 63 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

您现在可以生成并运行应用程序来测试。