Общий доступ к аудиофайлу Swift 4 (UIDocumentInteractionController) - PullRequest
0 голосов
/ 06 ноября 2018

У меня есть этот блок кода из предыдущего проекта, я планирую отправить аудиофайл (mp3) по UIDocumentInteractionController, но мне особенно нужно, чтобы это показало также возможность поделиться с WhatsApp. Кроме того, я добавил UIAlertView, который с 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: "")
                }
            }
         }
      }

1 Ответ

0 голосов
/ 06 ноября 2018

Сначала вам нужно будет добавить WhatsApp в ваш файл info.plist в массиве LSApplicationQueriesSchemes, чтобы вашему приложению было разрешено запрашивать схему whatsapp.

Тогда вот ваш код обновлен для Swift 4.2, «делать» бесполезно, и я использую 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. Я не трогал код вашего аудио файла, потому что ничего не знаю об этом.

...