Last active
November 28, 2021 04:00
-
-
Save bdashore3/d0dd8cf799287b8973a9ffa49fc7063f to your computer and use it in GitHub Desktop.
AlamoFire UI lockup fix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import Alamofire | |
import Combine | |
struct ContentView: View { | |
@StateObject var viewModel: ViewModel = ViewModel() | |
@State private var showAlert = false | |
@State private var downloadProgress: Double = 0.0 | |
var body: some View { | |
VStack { | |
Button("Show Alert") { | |
showAlert.toggle() | |
} | |
Button("Start download") { | |
viewModel.startDownload() | |
} | |
if viewModel.showProgressView { | |
ProgressView("Downloading…", value: viewModel.downloadProgress, total: 1.0) | |
.progressViewStyle(.linear) | |
} | |
} | |
.alert(isPresented: $showAlert) { | |
Alert( | |
title: Text("Text"), | |
message: Text("Dismiss this"), | |
dismissButton: .cancel() | |
) | |
} | |
} | |
} | |
class ViewModel: ObservableObject { | |
@Published var showProgressView: Bool = false | |
@Published var downloadProgress = 0.0 | |
func startDownload() { | |
let queue = DispatchQueue(label: "net", qos: .userInitiated) | |
showProgressView.toggle() | |
let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory) | |
var last = Date() | |
AF.download("https://speed.hetzner.de/100MB.bin", to: destination) | |
.downloadProgress { progress in | |
print(progress.fractionCompleted) | |
if Date().timeIntervalSince(last) > 1 { | |
last = Date() | |
DispatchQueue.main.async { | |
self.downloadProgress = progress.fractionCompleted | |
} | |
} | |
} | |
.response(queue: queue) { response in | |
print(response) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment