ios - 使用 UIActivityViewController/UIDocumentInteractionController 的文件共享不起作用 - [无法通过 AirDrop、Whatapp、iMessage、Mail 等共享]
问题描述
在尝试使用设备的共享表功能共享我下载到我的应用程序的“.mp3”文件时,我能够从文档目录中获取文件但无法共享它。
当我尝试通过 Whatsapp 分享它时,我收到一条错误消息:
此项目无法共享。请选择其他项目。
如果我通过 AirDrop 共享,它只会显示“失败”(红色),通过其他选项共享会导致一条空白消息(例如,一封没有附加文件的新电子邮件或一个没有任何内容的新消息)
以下是我迄今为止尝试过的代码选项:
选项 1 - 使用 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)
选项 2 - 使用 UIDocumentInteractionController
let docController : UIDocumentInteractionController?
docController = UIDocumentInteractionController(url: URL(string: fileToSharePath)!)
docController?.delegate = self
docController?.presentOptionsMenu(from: self.view.frame, in:self.view, animated:true)
在这两个选项中,我确实获得了文件,但无法共享它。手机确实将共享识别为音频文件,但我对此无能为力。
示例网址:
file:///Users/UserName/Library/Developer/CoreSimulator/Devices/C8B09E62-091F-4E61-BA6C-3D9EC23LKC01/data/Containers/Data/Application/EF2CKKJF-AB35-55G5-B778-439812EFGGG5/Documents/audioFile.mp3
共享适用于文本,但不适用于音频文件。
我是否还需要启用某些功能或向 AppDelegate 添加一些代码?
感谢任何帮助。谢谢。
更新 #1:来自@dfd 建议的代码[仍然不起作用]
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)
}
此外,对于所有这些选项,我在共享表中将音频文件 (mp3) 作为“音频录制”。
解决方案
您可以尝试在临时目录中创建此文件的副本并共享该副本,而不是共享原始文件。完成共享后,您可以将其删除或留给系统进行删除。
像这样的东西(您可以添加更多关于文件和目录存在的检查):
let fileManager = FileManager.default
let tempDirectory = fileManager.temporaryDirectory
let tempPath = tempDirectory.path + "/" + fileToSharePath.lastPathComponent
let tempURL = URL(fileURLWithPath: tempPath)
try? fileManager.copyItem(atPath:fileToSharePath.path , toPath: tempPath)
let docController : UIDocumentInteractionController?
docController = UIDocumentInteractionController(url: URL(string: tempURL)!)
docController?.delegate = self
docController?.presentOptionsMenu(from: self.view.frame, in:self.view, animated:true)
推荐阅读
- python - What would be the python function that returns a list of elements that only appear once in a list
- r - R:在 0 x 0 矩阵上调用 apply 会导致调用 FUN(numeric(0))。为什么?这可以预防吗?
- c - 我在 C 中的函数出现问题,尝试使用较小的块方法计算回归斜率。谁能帮我找出我的错误?
- java - 每次在 Snake 游戏中增长时,都希望提高 Snake 的速度
- xamarin.forms - Xamarin 表单的 Wootric 集成
- python - 用相应属性的其他行的值有效地填充 df nan 字段?
- swift - 如何在 for 循环中排序(swift)
- c++ - 如何在 C++ 中读取以空格分隔且数据量不确定的文本文件?
- xgboost - 是否需要将值转换为 xgboost 的百分比?
- wordpress - 提取 WordPress 插件的数据