How do I share an Audio File in an App using Swift 3?

4.7k views Asked by At

Sharing an Audio File in Swift

How do I share an audio file which exists in my apps document directory to other apps?

To elaborate on this question, what I mean is when a user taps a share button in the app they should be able to email their recorded audio track to another person, or alternatively to be able to send it across to a range of other apps which can handle audio like perhaps soundcloud.

Researching the topic, I have found:

  • UIActivityViewController
  • UIDocumentInteractionController

Since my application makes an audio recording of a person's voice which they should be able to share, and despite searching through stack overflow, I have not been able to find a code example of how exactly this option can be implemented in a Swift app. Can I request suggestions and example code on how this may be accomplished. Many Thanks,

2

There are 2 answers

0
Stephen Clark On

My answer is using for doing this with UIDocumentInteractionController.

I begin by instantiating a UIDocumentInteractionController at the top of my class

var controller = UIDocumentInteractionController()

Then I link up an IBAction to a share button on my nib or Storyboard:

@IBAction func SHARE(_ sender: Any) {
    let dirPath: String = NSSearchPathForDirectoriesInDomains(.documentDirectory,
                                                      .userDomainMask,
                                                      true)[0]
    let recordingName = UserDefaults.standard.string(forKey: "recordingName")
    let pathArray: [String] = [dirPath, recordingName!]
    let filePathString: String = pathArray.joined(separator: "/")
    controller = UIDocumentInteractionController(url: NSURL(fileURLWithPath: filePathString) as URL)
    controller.presentOpenInMenu(from: CGRect.zero,
                                 in: self.view,
                                 animated: true)     
}
0
miragessee On

Swift 3.x:

        let activityItem = URL.init(fileURLWithPath: Bundle.main.path(forResource: "fileName", ofType: "mp3")!)

        let activityVC = UIActivityViewController(activityItems: [activityItem],applicationActivities: nil)
        activityVC.popoverPresentationController?.sourceView = self.view

        self.present(activityVC, animated: true, completion: nil)