ProgressView Not Updating During Data Parsing in SwiftUI

It’s hard to reproduce the full code, but I’ll try to explain the issue clearly.

I’m trying to display a progress bar view to show the status of parsing some data downloaded online. The function I use for parsing correctly prints the download percentage in the console, but for some reason, my progress view doesn’t update.

The downloadData function has an escaping closure to report the stages of the download (downloadData, parseData, savingData).

When downloading data, the ProgressView updates correctly. However, when the downloadStage is in the parseData stage, nothing updates in the view. I see the ProgressView says “Parsing Data,” but the value doesn’t change. The console prints the data, so I’m sure the data is correctly passed into the view.

What could be the issue?

I’ve noticed that if I insert a small delay in my code, the ProgressView updates. How can I ensure the view updates correctly?


  // MARK: - Download Data
    func downloadData(lista: PlayListModel, completion: @escaping (_ stage: DownloadStage, _ progress: Double, _ total: Int) -> Void) async throws {
        
        
        do {
            var m3uString = ""
            // RUN as 1st
            m3uString = try await requestM3UListAlamo(from: lista.playlistUrl, progressHandler: { progress in
                
                completion(.downloadData, progress, 100)
                
            })
            
            completion(.parseData, 0, 0)
// At this point func don't update the UI 
            let group = try await sdparsePlaylist(m3uContent: m3uString) { progress, total in
                completion(.parseData, progress, Int(total))
            }
            
            completion(.savingData, 0.0, 0)
            
            try await saveData(lista: lista, grouped: group) { stage, result in
                
                completion(stage, 100, 100)

            }
            
            
        } catch {
            
            // Handle failure and update completion stage
            print("Download failed with error: (error.localizedDescription)")
            completion(.fail, 0, 0)
            
            throw error // Propagate error to caller
        }
    }
    

  func sdparsePlaylist(m3uContent: String, completion: @escaping (_ progress: Double, _ total: Int) -> Void) async throws -> [String: [PlaylistItem]] {
        print("4-------------- parsing playlist --------------")
        var appoggio: [String: [PlaylistItem]] = [:]
        let createDate = Date()

        do {
            let playlist = try await self.parser.parse(m3uContent)
            let media = playlist.medias
            let totalItems = media.count
            var progress = 0
            
            for item in media {
                let attributes = item.attributes
                let groupTitle = attributes.groupTitle ?? "NOT CLASSIFIED"
                let playlistItem = PlaylistItem(duration: item.duration, tvgId: attributes.id, tvgName: attributes.name, tvgCountry: attributes.country, tvgLanguage: attributes.language, tvgLogo: attributes.logo, tvgChno: attributes.channelNumber, tvgShift: attributes.shift, groupTitle: groupTitle, seasonNumber: attributes.seasonNumber, episodeNumber: attributes.episodeNumber, kind: item.kind.rawValue, url: item.url, lastPlay: createDate)
                
                if var existingPlaylist = appoggio[groupTitle] {
                    existingPlaylist.append(playlistItem)
                    appoggio[groupTitle] = existingPlaylist
                } else {
                    appoggio[groupTitle] = [playlistItem]
                }
                
                
                let currentProgress = Double(progress) / Double(totalItems) * 100
                completion(currentProgress, 100)
                print("parser background: (currentProgress)% ((progress + 1) / (totalItems))")
                progress += 1
                
            }
        } catch {
            print(error.localizedDescription)
            throw error
        }
       
        return appoggio
    }

The View:

import SwiftUI
import SwiftData
import Alamofire

struct AddNewPlaylist: View {
    @Environment(.modelContext) private var modelContext
    @State private var playlistName = "TV"
@State private var playlistUrl = "https://country.m3u"

    
    @State var downloadStage: DownloadStage = .none
    @State var progress: CGFloat = 0.5
    @State var total = 0
    @Binding var isPresented: Bool
    @State var bounce = false
    @State private var showAlert = false
    @State private var alertMessage = ""
    let backgroundParser: BackgroundParser
    
    var body: some View {
        VStack {
            Text("Add New Playlist")
                .foregroundStyle(Color("Text1"))
                .font(.title)
                .padding()
            
            Spacer()
            
            TextField("Playlist Name", text: $playlistName)
                .padding()
                .background(RoundedRectangle(cornerRadius: 10).stroke(Color.white, lineWidth: 1))
                .foregroundStyle(Color("Text1"))
            TextField("M3U Link", text: $playlistUrl)
                .padding()
                .background(RoundedRectangle(cornerRadius: 10).stroke(Color.white, lineWidth: 1))
                .foregroundStyle(Color("Text1"))
                .overlay {
                    HStack {
                        Spacer()
                        if !playlistUrl.isEmpty {
                            Button(action: {
                                self.playlistUrl = "" // Clear the text
                            }) {
                                Image(systemName: "multiply.circle.fill")
                                    .foregroundColor(.gray)
                            }
                            .padding(.trailing, 8)
                        }
                    }
                }
            HStack {
                Button {
                    Task {
                        await backgroundParser.cancelDownload()
                        isPresented = false
                    }
                } label: {
                    Text("Return")
                }
                .buttonStyle(BorderedButtonStyle())
                .foregroundStyle(Color("Text1"))
                
                Spacer()
                
                Button("Save") {
                    if playlistName != "" && playlistUrl != "" {
                        Task {
                            do {
                                let playlist = PlayListModel(timestamp: Date(), playlistName: playlistName, playlistUrl: playlistUrl, lastUpdate: Date())
                                try await backgroundParser.downloadData(lista: playlist) { stage, prog, total in
                                    // print correcctly but the view dont update
                                    print("going tp update (stage.description), (prog), (total)")
                                    self.downloadStage = stage
                                    self.progress = prog
                                    self.total = total
                                    
                                    if stage == .done {
                                        isPresented = false
                                    }
                                    
                                }
                            } catch {
                                    alertMessage = "Error: (error.localizedDescription)"
                                    showAlert = true
                            }
                        }
                    }
                }
                .buttonStyle(BorderedButtonStyle())
                .foregroundStyle(Color("Text1"))
                .alert(isPresented: $showAlert) {
                    Alert(title: Text("Error"), message: Text(alertMessage), dismissButton: .default(Text("OK")))
                }
            }
            .padding(.top, 50)
            
            Spacer()
            
            
            VStack{
                switch downloadStage {
                    
                case .downloadData:
                
                    ProgressView(value: progress, total: CGFloat(total)) {
                        HStack {
                            Text("Downloading Data...").font(.title3)
                            Text("(Int(progress)) / (total)")
                        }
                    }.progressViewStyle(.linear)
                    
                case .parseData:
                    // Here no work --------------------------------------
                    ProgressView(value: progress, total: 100) {
                        HStack {
                            Text("Parsing Data...").font(.title3)
                            Text("(Int(progress)) / (total)")
                        }
                    }.progressViewStyle(.linear)
                
                case .savingData:
                        HStack {
                            Text("Saving data...don't close window").font(.title3)
                           
                        }
                default:
                    
                    Text("")
                }
            }.foregroundColor(.white)
            
            
            Spacer()
        }
        .padding()
        .background {
            LinearGradient(colors: [.color1, .color2, .color3], startPoint: .bottom, endPoint: .topTrailing)
                .ignoresSafeArea()
        }
    }
}


Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật