首页 > 解决方案 > 使用 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) 作为“音频录制”。

标签: iosswiftuiactivityviewcontrollerios-sharesheetuidocumentinteractioncontroller

解决方案


您可以尝试在临时目录中创建此文件的副本并共享该副本,而不是共享原始文件。完成共享后,您可以将其删除或留给系统进行删除。

像这样的东西(您可以添加更多关于文件和目录存在的检查):

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)

推荐阅读