Swift 4 分享音频文件(UIDocumentInteractionController)

Swift 4 sharing audio file (UIDocumentInteractionController)

我有之前项目的这段代码,我的计划是通过 UIDocumentInteractionController 发送一个音频文件 (mp3),但我特别需要它显示通过 WhatsApp 共享的可能性。另外,我添加了一个 UIAlertView ,因为 ios9 已被弃用。您可能已经意识到,这段代码有点像 "old"。因此,如果您能提出任何使它像现在一样工作的选项,我将不胜感激,因为在 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 协议。我没有接触你的音频文件的代码,因为我对此一无所知。