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

强颜欢笑 提交于 2019-12-01 07:42:21

问题


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,


回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/41263742/how-do-i-share-an-audio-file-in-an-app-using-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!