Hello community! I have a view with a task that takes a long time. At the time when the task finishes, the View might not be shown on the screen, so kind of is in the background.
I want to execute a function once this task is done. How can I do that? (most of the code is probably not relevant, just scroll down until you see the comment β how to execute function here β
I have tried using a background thread, but I am not even sure if this has to do with the problem. Any tips?
import SwiftUI
import PhotosUI
struct VideoPicker: UIViewControllerRepresentable{
// @Binding var videoURL:String?
@Binding var videoURL2: URL?
func makeUIViewController(context: Context) -> PHPickerViewController {
var config = PHPickerConfiguration()
config.filter = .videos
let picker = PHPickerViewController(configuration: config)
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator:NSObject, PHPickerViewControllerDelegate{
let parent:VideoPicker
init(_ parent: VideoPicker){
self.parent = parent
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true) {
// do something on dismiss
}
guard let provider = results.first?.itemProvider else {return}
provider.loadFileRepresentation(forTypeIdentifier: "public.movie") { url, error in
guard error == nil else{
print("error in video picker")
return
}
// receiving the video-local-URL / filepath
guard let url = url else {
print("error 2 in video picker")
return
}
print("original url \(url)")
let fileName = "\(Int(Date().timeIntervalSince1970)).\(url.pathExtension)"
let newUrl = URL(fileURLWithPath: NSTemporaryDirectory() + fileName)
try? FileManager.default.copyItem(at: url, to: newUrl)
// self.parent.videoURL = newUrl.absoluteString
self.parent.videoURL2 = newUrl
// HOW TO EXECUTE FUNCTION HERE?
}
}
}
}
struct ParentView: View {
@State var videoURL2 : URL?
var body: some View {
VideoPicker(videoURL2: $videoURL2)
.onChange(of: videoURL2) { newValue in
//THIS IS HOW I EXECUTE THE FUNC AT THE MOMENT
if videoURL2 != nil{
function(videoURL: videoURL2!)
} else {return}
}
}
My current ,solution" only works if ParentView stays opened during the whole task. The line
self.parent.videoURL2 = newUrl
gets executed either way tough, but the .onChange does not react.