While trying to share an '.mp3' file that I have downloaded onto my app using the device's share-sheet feature, I'm able to fetch the file from the documents directory but unable to share it.
When I try to share it via Whatsapp, I get an error saying:
This item cannot be shared. Please select a different item.
If I share via AirDrop, it just says "Failed" (in red) and sharing via other options leads to a blank message (e.g. a new email with no file attached or a new msg with nothing in it)
Here are the code options I've tried so far:
Option 1 - Using UIActivityViewController
let fileURL = NSURL(fileURLWithPath: FileURLFromDocumentsDirectory)
var filesToShare = [Any]()
filesToShare.append(fileURL)
let activityViewController = UIActivityViewController(activityItems: filesToShare, applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
Option 2 - Using UIDocumentInteractionController
let docController : UIDocumentInteractionController?
docController = UIDocumentInteractionController(url: URL(string: fileToSharePath)!)
docController?.delegate = self
docController?.presentOptionsMenu(from: self.view.frame, in:self.view, animated:true)
In both options, I do get the file but can't share it. The phone does recognize the share as an audio file but I can't do anything with it.
Sample URL:
file:///Users/UserName/Library/Developer/CoreSimulator/Devices/C8B09E62-091F-4E61-BA6C-3D9EC23LKC01/data/Containers/Data/Application/EF2CKKJF-AB35-55G5-B778-439812EFGGG5/Documents/audioFile.mp3
The sharing works for text but not for the audio files.
Do I also need to enable some features or add some code to the AppDelegate?
Appreciate any help. Thanks.
Update #1: Code with Suggestions from @dfd [still doesn't work]
let shareAction = UIContextualAction(style: .normal, title: "Share") { (action, view, completionHandler) in
let fileURL = NSURL(fileURLWithPath: (downloadedFile?.documentDirectoryURL)!)
let activityViewController = UIActivityViewController(activityItems: [fileURL], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
}
Also, for all these options, I get the audio file (mp3) as an 'Audio Recording' in the Share Sheet.