I'm looking for an event in the life-cycle of a view in SwiftUI, that is equivalent to viewWillAppear(). Yes, I know there is an ".OnAppear" in SwiftUI, but that is like viewDidAppear. Is there a workaround to do get that specific execution time before view is loaded?
Asked
Active
Viewed 6,639 times
10
-
2You might be able to fake it by doing something in the `init` of an `ObservableObject` stored as a `@StateObject`. Can you elaborate on your use case or what you're trying to avoid by using `onAppear`? – jnpdx May 17 '21 at 18:22
-
Need to load some data and images from web. I'll try your idea. thnx – Ethan Halprin May 17 '21 at 18:37
-
1But why not use `onAppear` for that? The loading will take a non-zero amount of time, and the returns from any network load like that will be asynchronous, so you aren't blocking anything... – jnpdx May 17 '21 at 18:43
-
First, of course it's asynchronous (A Combine's DataTaskPublisher). Secondly, why do I need to wait for the view to load? I rather start the GET call as soon as possible. What if there will be a lot of data to fetch? – Ethan Halprin May 17 '21 at 18:58
-
Does this answer your question https://stackoverflow.com/a/59746380/12299030? – Asperi May 17 '21 at 19:00
-
"As soon as possible" is likely to be the difference of milliseconds, if that. SwiftUI views are loaded and put into the view hierarchy sometimes as much as 60-120 times per second. `onAppear` is not likely to give you a big performance hit. I get what you're saying with wanting to accomplish it quickly, but it's likely to be an order (or many orders) of magnitude smaller than the time the network calls take. The amount of data doesn't seem relevant to where you start the calls. – jnpdx May 17 '21 at 19:01
-
Asperi thanks! (It's not pure SwiftUI but solves the case) – Ethan Halprin May 17 '21 at 19:10
1 Answers
-3
Try this modifier:
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
// your code
}

rgreso
- 496
- 1
- 7
- 19
-
6`willEnterForegroundNotification` is not the same as `viewWillAppear` – Tung Fam Jun 28 '22 at 15:32