swiftswiftuiavaudioplayer

Download length from track makes app to freeze SwiftUI


I've been searching for a method how to display track length from URL that is stored on the server. I found this method in Swift: AVPlayer - How to get length of mp3 file from URL? working fine:

let item = AVPlayerItem(url: url)
let duration = Double(item.asset.duration.value) / Double(item.asset.duration.timescale)

Here's the problem: this peace of code completely freezes the app when I navigate to views where it shows. How can I fix this problem?

Adding the function:

func getDuration(url: URL) -> Double {
    let item = AVPlayerItem(url: url)
    let duration = Double(item.asset.duration.value) / Double(item.asset.duration.timescale)
    return duration
}

Text itself:

                        Text(String(audioManager.getDuration(url: URL(string: "http://gameleprilucky.ru/soungs/" + (data.linkSoung ?? "abob"))!)))
                            .font(.custom("Manrope-Medium", size: 12))
                            .foregroundColor(.white)

Solution

  • Those lines certainly shouldn't be called on UI thread and it is certain to cause unresponsive interface.

    You should to the following: