ios - Swift 4 共享音频文件(UIDocumentInteractionController)
问题描述
我有这个来自以前项目的代码块,我的计划是通过 发送音频文件(mp3)UIDocumentInteractionController
,但我特别需要显示通过 WhatsApp 共享的可能性。另外,我添加了一个UIAlertView
which 因为 ios9 已被弃用。您可能已经意识到,这段代码有点“旧”。因此,如果您能建议任何选项使其像现在一样工作,我将不胜感激,因为在 swift 4 中,它没有。
var documentationInteractionController: UIDocumentInteractionController?
@IBAction func ShareButton(_ sender: Any) {
do {
if let aString = URL(string: "whatsapp://app") {
if UIApplication.shared.canOpenURL(aString) {
var savePath = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/whatsAppTmp.waa").absoluteString
savePath = Bundle.main.path(forResource: "FILENAME", ofType: "mp3") ?? ""
documentationInteractionController = UIDocumentInteractionController(url: URL(fileURLWithPath: savePath))
documentationInteractionController?.uti = "net.whatsapp.audio"
documentationInteractionController?.delegate = self as? UIDocumentInteractionControllerDelegate
documentationInteractionController?.presentOpenInMenu(from: CGRect(x: 0, y: 0, width: 0, height: 0), in: view, animated: true)
} else {
_ = UIAlertView(title: "Error", message: "No WhatsApp installed on your iPhone", delegate: (self as! UIAlertViewDelegate), cancelButtonTitle: "OK", otherButtonTitles: "")
}
}
}
}
解决方案
首先,您需要在LSApplicationQueriesSchemes
数组中的 info.plist 文件中添加 WhatsApp,以便允许您的应用程序查询计划 whatsapp。
然后这是您为 Swift 4.2 更新的代码,“do”没用,我使用 UIAlertController。
@IBAction func share(_ sender: UIButton) {
if let aString = URL(string: "whatsapp://app") {
if UIApplication.shared.canOpenURL(aString) {
var fileUrl = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/whatsAppTmp.waa").absoluteString
fileUrl = Bundle.main.path(forResource: "FILENAME", ofType: "mp3") ?? ""
documentationInteractionController = UIDocumentInteractionController(url: URL(fileURLWithPath: fileUrl))
documentationInteractionController?.uti = "net.whatsapp.audio"
documentationInteractionController?.delegate = self
documentationInteractionController?.presentOpenInMenu(from: CGRect(x: 0, y: 0, width: 0, height: 0), in: view, animated: true)
} else {
let alert = UIAlertController(title: "Error", message: "No WhatsApp installed on your iPhone.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .default, handler: { _ in
NSLog("The \"OK\" alert occured.")
}))
self.present(alert, animated: true, completion: nil)
}
}
}
不要忘记采用UIDocumentInteractionControllerDelegate
协议。我没有触摸您的音频文件的代码,因为我对此一无所知。
推荐阅读
- c# - 在 asp.net core v5.0 中,在域/端口导致 404 之后,url 多个斜杠
- amazon-web-services - 将环境变量从 AWS Codepipeline 传递到 CodeBuild
- python - 如何打印每个值与最高值的差异?
- system-verilog - 是否允许在端口中使用打包的结构?
- python - 如何生成所有有效的数字表达式?
- c++ - When I try to write to wav in c++, it says corrupt file
- oop - 确定海龟集群的数量
- reactjs - MobX 可观察更改未更新 UI/重新渲染
- android - ViewModelProvider.get 总是给出未解决的参考
- c# - 无法使用 .NET Core 控制台应用程序从 AWS ECS 任务访问 SSM