3

I created a file and I want to share it via UIDocumentInteractionController.

I am unsure on how to obtain the URL from the documentsPath and destination path where I saved my file

        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)
            

1 Answer 1

7

Revise your code to the following

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

}

Now wire up the IBAction to a button in the storyboard. Next:

  1. click on the blue project icon in the left sidebar and then select Info from the horizontal menu.
  2. expand Document Types and enter "txt" in the Name field and "public.data, public.content" in the Types field
  3. now expand Exported UTIs and enter "txt" in the Description field, "kUTTypeText" in the Identifier field and "public.data, public.content" in the Conforms to field

So that everything looks like this:

enter image description here

You can now build and run the app to test.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.