首页 > 解决方案 > Swift 4 共享音频文件(UIDocumentInteractionController)

问题描述

我有这个来自以前项目的代码块,我的计划是通过 发送音频文件(mp3)UIDocumentInteractionController,但我特别需要显示通过 WhatsApp 共享的可能性。另外,我添加了一个UIAlertViewwhich 因为 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: "")
                }
            }
         }
      }

标签: iosxcodeswift4whatsapp

解决方案


首先,您需要在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协议。我没有触摸您的音频文件的代码,因为我对此一无所知。


推荐阅读