Post

Replies

Boosts

Views

Activity

Preventing crashes with ScrollViewProxy.scrollTo()
I have a search field and a List of search results. As the user types in the search field, the List is updated with new results. Crucially, with each update, I want to reset the List's scroll position back to the top. To achieve this, I'm using the following .onChange() modifier along with a ScrollViewReader: .onChange(of: searchQuery) { _, newQuery in Task { searchResults = await searchLibrary(for: newQuery) scrollViewProxy.scrollTo(0, anchor: .top) } } My List uses index-based IDs, so scrolling to 0 should always go to the first item. The above code works, but crashes if searchResults is empty because there is no item in the List with an ID of 0. (As a side note, it seems rather excessive for the scrollTo() method to trigger a full-on crash just because the ID is not found; I don't think this should be anything more than a warning, or the method should throw an error that can be caught). To work around this, I added an isEmpty check, so we only attempt the scroll if the array is not empty: .onChange(of: searchQuery) { _, newQuery in Task { searchResults = await searchLibrary(for: newQuery) if !searchResults.isEmpty { scrollViewProxy.scrollTo(0, anchor: .top) } } } However, even with this check, I was seeing rare crashes in production, consistent with a race condition. My guess is that when searchResults is updated, the view is not recreated immediately, so if scrollTo() is called too quickly, the List may not yet be seeing the latest update to the searchResults array. I figured that I could try to delay the calling of scrollTo() to give the view time to update: .onChange(of: searchQuery) { _, newQuery in Task { searchResults = await searchLibrary(for: newQuery) if !searchResults.isEmpty { DispatchQueue.main.async { scrollViewProxy.scrollTo(0, anchor: .top) } } } } However, even with this, I've just received a crash report pointing to the same issue (the first in about four months). I'm not able to reproduce the bug myself – so it definitely seems like a rare race condition, probably relating to the timing of view updates. I guess, I can insert another isEmpty check before calling scrollTo(), but I'm starting to wonder if it's even possible to guarantee that the item will be in the List when scrollTo() performs its action, and because this is so hard to reproduce, I can't really test any ideas. Does anyone have any idea how (and at what point) the ScrollViewReader reads the view's current state? What's the right way to approach debugging a problem like this? Moreover, does anyone have any better suggestions about how to handle resetting the List position? The reason I want to do this is because, if the user types, scrolls a bit, and then types some more, the new results appear above the fold where the user can't see them, leading to a confusing experience. I thought about switching to the newer .scrollPosition() modifier, but that's only iOS 18+ and only for ScrollViews, not Lists. Cheers!
Topic: UI Frameworks SubTopic: SwiftUI
0
0
18
1d
BGContinuedProcessingTask expiring unpredictably
I've adopted the new BGContinuedProcessingTask in iOS 26, and it has mostly been working well in internal testing. However, in production I'm getting reports of the tasks failing when the app is put into the background. A bit of info on what I'm doing: I need to download a large amount of data (around 250 files) and process these files as they come down. The size of the files can vary: for some tasks each file might be around 10MB. For other tasks, the files might be 40MB. The processing is relatively lightweight, but the volume of data means the task can potentially take over an hour on slower internet connections (up to 10GB of data). I set the totalUnitCount based on the number of files to be downloaded, and I increment completedUnitCount each time a file is completed. After some experimentation, I've found that smaller tasks (e.g. 3GB, 10MB per file) seem to be okay, but larger tasks (e.g. 10GB, 40MB per file) seem to fail, usually just a few seconds after the task is backgrounded (and without even opening any other apps). I think I've even observed a case where the task expired while the app was foregrounded! I'm trying to understand what the rules are with BGContinuedProcessingTask and I can see at least four possibilities that might be relevant: Is it necessary to provide progress updates at some minimum rate? For my larger tasks, where each file is ~40MB, there might be 20 or 30 seconds between progress updates. Does this make it more likely that the task will be expired? For larger tasks, the total time to complete can be 60–90 mins on slower internet connections. Is there some maximum amount of time the task can run for? Does the system attempt some kind of estimate of the overall time to complete and expire the task on that basis? The processing on each file is relatively lightweight, so most of the time the async stream is awaiting the next file to come down. Does the OS monitor the intensity of workload and suspend the task if it appears to be idle? I've noticed that the task UI sometimes displays a message, something along the lines of "Do you want to continue this task?" with a "Continue" and "Stop" option. What happens if the user simply ignores or doesn't see this message? Even if I tap "Continue" the task still seems to fail sometimes. I've read the docs and watched the WWDC video, but there's not a whole lot of information on the specific issues I mention above. It would be great to get some clarity on this, and I'd also appreciate any advice on alternative ways I could approach my specific use case.
7
0
269
1w
Correctly initializing observable classes in modern SwiftUI
I have two @Observable manager classes, which share a reference to a third class. I initialize this setup using a custom init in my App struct, like so: @main struct MyApp: App { private let managerA: ManagerA private let managerB: ManagerB init() { let managerC = ManagerC() self.managerA = ManagerA(managerC: managerC) self.managerB = ManagerB(managerC: managerC) } var body: some Scene { WindowGroup { ContentView() .environment(managerA) .environment(managerB) } } } I've been using this pattern for some time and it has been working fine. However, I just today discovered that @Observable objects are supposed to be initialized as @State vars, as shown in Apple's documentation here. This means I shoud be doing the following: @main struct MyApp: App { @State private var managerA: ManagerA @State private var managerB: ManagerB init() { let managerC = ManagerC() self.managerA = ManagerA(managerC: managerC) self.managerB = ManagerB(managerC: managerC) } var body: some Scene { WindowGroup { ContentView() .environment(managerA) .environment(managerB) } } } I've also seen some examples where the @State vars are initialized manually like this: @main struct MyApp: App { @State private var managerA: ManagerA @State private var managerB: ManagerB init() { let managerC = ManagerC() let managerA = ManagerA(managerC: managerC) let managerB = ManagerB(managerC: managerC) self._managerA = State(initialValue: managerA) self._managerB = State(initialValue: managerB) } var body: some Scene { WindowGroup { ContentView() .environment(managerA) .environment(managerB) } } } ChatGPT tells me the third approach is the correct one, but I don't understand why and ChatGPT can't produce a convincing explanation. The compiler doesn't produce any errors or warnings under each approach, and as far as I can tell, they all behave identically with no discernible difference in performance. Does it matter which pattern I use? Is there a "correct" way?
2
0
67
Nov ’25
iOS 26 regression: Slider does not respect step parameter
In iOS 26, the Slider control no longer respects the step parameter. For example, import SwiftUI struct ContentView: View { @State private var sliderValue: CGFloat = 16 var body: some View { Slider( value: $sliderValue, in: 0...100, step: 5, onEditingChanged: { editing in print(sliderValue) } ) } } In iOS 18, this prints values like 5, 35, 60, 95, etc. In iOS 26.0 (release version), this prints floats that are not rounded to the nearest 5, and the slider does not snap to values ending in 5. Feedback report number: FB20320542
Topic: UI Frameworks SubTopic: SwiftUI
6
4
308
Nov ’25
.glassProminent toolbar buttons are glitchy in iOS 26.1 RC
I've adopted the new .glassProminent button style for primary/confirmation actions in the toolbar. Starting around beta 3 or 4 of iOS 26.1, these buttons started glitching: When navigating to a view, the button is initially untinted, and then the tint abruptly appears after a 1 second delay. This is still the case in the 26.1 release candidate, and it is also affecting Apple's own apps. This new style is one of the defining characteristics of the new design system, so I find it hard to believe that Apple hasn't noticed this regression, which leads me to wonder if I might be doing something wrong or if this is specific to my device (12 mini). Is this the correct way to achieve the effect: ToolbarItem(placement: .confirmationAction) { Button("button_submit", action: submitMessage) .buttonStyle(.glassProminent) .tint(Color.blue) } The same glitch occurs if I use .primaryAction, and it also occurs even if I remove the .tint modifier. It seems to be a problem with .glassProminent. It looks really janky, so now I feel like I need to pull out all my .glassProminent toolbar buttons in preparation for iOS 26.1's release.
Topic: UI Frameworks SubTopic: SwiftUI
2
0
125
Oct ’25
AlarmKit alarm UI strings are lost after updating OS
I have a working AlarmKit app, but I've noticed that after any iOS update (e.g. the 26.0.1 update from a few days ago), my scheduled alarms seem to lose their UI strings, so instead of the Stop button saying "Stop", it says "alarm_ui_stop_button" (which is my localization key for the button text). If I delete the alarm and re-add it, then it works again... until the next software update. It seems like OS updates are interfering with the link between scheduled alarms and app localization strings, which I believe are dynamically looked up at alarm time (not at configuration time). I am settings the strings in the standard way like this: AlarmManager.AlarmConfiguration( schedule: .fixed(date), attributes: AlarmAttributes<SDAlarmMetadata>( presentation: AlarmPresentation( alert: AlarmPresentation.Alert( title: "alarm_ui_title", stopButton: .init(text: "alarm_ui_stop_button", textColor: .yellow, systemImageName: "xmark") ) ), metadata: SDAlarmMetadata(title: title, subtitle: subtitle), tintColor: .yellow ), sound: .default ) Has anyone else noticed this or found a workaround? I guess I could use localization keys that are identical to the desired text, but this would only work for one language.
3
0
146
Oct ’25
Navigation title renders below navigation bar background color in iOS 26
I've been trying to update my apps for iOS 26, and all summer I kept hitting this issue with the navigation bar title. I was hoping Apple would eventually fix it, but it still seems to be broken in beta 9, so now I'm wondering if I'm doing something wrong. Here's a minimal working example: struct ContentView: View { @State private var path = NavigationPath() var body: some View { NavigationStack(path: $path) { List { Text("Item 1") Text("Item 2") Text("Item 3") } .navigationTitle("Title") .toolbarBackground(Color(red: 0.5, green: 0.5, blue: 0.5), for: .navigationBar) .toolbarBackgroundVisibility(.visible, for: .navigationBar) } } } Expected result: The title should be rendered on a gray background. Actual result: The title is invisible because it is rendered below the gray background. If I modify the gray color with .opacity(0.5), then it becomes clear that the title is indeed present, but it's behind the background. This example works correctly in iOS 18. Is this an iOS 26 bug or is this a forbidden design now because everything has to be translucent?
Topic: UI Frameworks SubTopic: SwiftUI
2
2
289
Sep ’25
SwiftData migration plan in app and widget
I have an app and widget that share access to a SwiftData container using App Groups. I have implemented a SwiftData migration plan, but I am unsure whether I should allow the widget to perform the migration (in addition to the app). I am concerned about two possible issues: If the app and widget are run at approximately the same time (e.g. the user taps Open after doing a manual update in the App Store), then both the app and widget might try to perform the migration at the same time, which could lead to race conditions / data corruption. If the widget is first to run but the widget gets suspended for some reasons (e.g., iOS decides it's using too many resources), then the migration might be suspended leaving the database in an corrupted state. To me, it feels like the safest option is to only allow the app itself to perform the migration – this will ensure that the migration can only happen once in a safe state. However, this will lead to problems for the widget. For example, if the user does not open the app for several days after an automatic update, the widget will be in a broken state, since it will not be able to open the container until it has been migrated by the app. Possible solutions I'm considering: Allow both the app and widget to perform the migration and cross my fingers. (Ignore Issue 1 and Issue 2) Implement some kind of UserDefaults flag that is set to true during migration, so that the app and widget will avoid performing the migration concurrently. (Solves Issue 1 but not Issue 2) Only perform the migration in the app, and then add code to the widget to detect which container version the widget has access to, so that the widget can continue to work with a v1 container until the app eventually updates it to a v2 container. (Solves Issue 1 and Issue 2, but leads to very convoluted code – especially over time) Things I'm unsure about: Will iOS continue to use v1 of the widget until the app is opened for the first time, at which point v2 of the widget is installed? Or does iOS immediately update the widget to v2 on update? Does iOS immediately refresh the widget timeline on update? Does SwiftData already have some logic to avoid migrations being performed twice, even from different threads? If so, how does it respond if one process tries to access a container while another process is performing a migration? Does anyone have any recommendations about how to handle these possible issues? What are best practices? Cheers!
0
1
350
Nov ’24