melik ozbay
melik ozbay

Reputation: 31

Swift 4 Audio share with Whatsapp

I would like to share audio (.mp3) file via WhatsApp. I used UIActivityViewController but it just share mp3 files link not the file. How can i share the file to WhatsApp? There is my code:

 @IBAction func playTusu(_ sender: Any) {
    let url = URL(string: "https://freesound.org/data/previews/405/405511_2731495-lq.mp3")!
    let playerItem = CachingPlayerItem(url: url)

    playerItem.delegate = self

    player = AVPlayer(playerItem: playerItem)
    player.automaticallyWaitsToMinimizeStalling = false
    player.play()

}

@IBAction func paylas(_ sender: Any) {
    let url: [Any] = ["https://freesound.org/data/previews/405/405511_2731495-lq.mp3"]
    let avc = UIActivityViewController(activityItems: url, applicationActivities: nil)
    self.present(avc, animated: true)
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

Thanks.

Upvotes: 3

Views: 1725

Answers (1)

Yannick
Yannick

Reputation: 3278

In your paylas function you are trying to share a String but it should actually be a URL. The question has also been answered here: How do I share an Audio File in an App using Swift 3?

@IBAction func paylas(_ sender: Any) {
    let url: [Any] = [audioFileURL]
    let avc = UIActivityViewController(activityItems: url, applicationActivities: nil)
    self.present(avc, animated: true)
}

Update

The question says that you have a file but you only have the URL to the audio.

As @Leo Dabus mentioned in the comments, you have to download the audio and create a file first. Have a look at this SO question Download mp3 file. You also have to wait until the audio has downloaded. Then, you can share the file. Make sure to do that on the UI / Main Thread.

Upvotes: 2

Related Questions