Given that SwiftUI and modern programming idioms promote asynchronous activity, and observing a data model and reacting to changes, I wonder why it's so cumbersome in Swift at this point.
Like many, I have run up against the problem where you perform an asynchronous task (like fetching data from the network) and store the result in a published variable in an observed object. This would appear to be an extremely common scenario at this point, and indeed it's exactly the one posed in question after question you find online about this resulting error:
Publishing changes from background threads is not allowed
Then why is it done? Why aren't the changes simply published on the main thread automatically?
Because it isn't, people suggest a bunch of workarounds, like making the enclosing object a MainActor. This just creates a cascade of errors in my application; but also (and I may not be interpreting the documentation correctly) I don't want the owning object to do everything on the main thread.
So the go-to workaround appears to be wrapping every potentially problematic setting of a variable in a call to DispatchQueue.main. Talk about tedious and error-prone. Not to mention unmaintainable, since I or some future maintainer may be calling a function a level or two or three above where a published variable is actually set. And what if you decide to publish a variable that wasn't before, and now you have to run around checking every potential change to it?
Is this not a mess?
Explore the various UI frameworks available for building app interfaces. Discuss the use cases for different frameworks, share best practices, and get help with specific framework-related questions.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Running up Xcode 16.2 Beta 1, a lot of my code that used onPreferenceChange in Views to change @State properties of those views, such as some notion of a measured width is now complaining about mutating the @MainActor-isolated properties from Sendable closures.
Now I've got to hoop-jump to change @State properties from onPreferenceChange? OK, but seems a bit of extra churn.
A few days ago scanning NFC tags or QR codes for AppClips with advanced experiences started showing the error "The operation couldn't be completed. (CPSErrorDomain error 2.)" in the AppClip sheet as seen here:
We are providing AppClips to our customers and they trust AppClips to always work, since it is a big part of their business.
Since this is happening at our customers phones and on the phones of their customers, I don't have a sysdiagnose.
I already created a feedback entry about this FB16601674.
We checked everything, our AASA file, the Appstore Experiences.
I have something that looks like:
NavigationStack {
List(self.items, id: \.self, selection: self.$selectedItems) { item in
NavigationLink {
ItemView(item: item)
.environment(\.managedObjectContext, self.viewContext)
} label: {
LabelWithMenuView(object: item) { ptr in
self.labelHandler(item: item, newName: ptr)
}
}
}
if self.editMode?.wrappedValue == .active {
editButtons
} else {
TextField("Add Item", text: self.$newItem)
.onSubmit {
self.addItem()
self.newItem = ""
}
.padding()
}
}
#if os(iOS)
.toolbar {
EditButton()
}
.onChange(of: self.editMode?.wrappedValue) { old, new in
print("editMode \(old) -> \(new)")
}
#endif
With that layout, the edit button doesn't show up at all; if I put it as part of the List, it does show up, but the first click doesn't do anything; after that, it works, but the onChange handler doesn't show it getting changed, and the editButtons don't go away.
Hello. There seems to be a bug specifically in the iOS 18.2 (both Beta 1 and 2) and not seen in the previous versions.
The bug is: when LazyVGrid is nested inside NavigationStack and some elements of the LazyVGrid have animations, navigating into any nested view and then going back to the initial view with the LazyVGrid causes all animations to stop working.
Here is the example code inline:
struct ContentView: View {
@State private var count: Int = 0
var body: some View {
NavigationStack {
LazyVGrid(
columns: Array(
repeating: GridItem(spacing: 0),
count: 1
),
alignment: .center,
spacing: 0
) {
VStack {
Text(String(count))
.font(.system(size: 100, weight: .black))
.contentTransition(.numericText())
.animation(.bouncy(duration: 1), value: count)
Button("Increment") {
count += 1
}
NavigationLink(destination: { Text("Test") }, label: { Text("Navigate") })
}
}
}
.padding()
}
}
Once you run the application on iOS 18.2 Beta (I've tried on a real device only), the steps to reproduce are:
Tap on the "Increment button"
You should see the number change with an animation
Tap on the "Navigate" button
Tap "Back" to go to the initial screen
Tap "Increment" again
The number changes without an animation
I can confirm that this affects not only .contentTransition() animation but any animation within the LazyVGrid, I've tested this in my real app.
Let me know if I can provide more details. Thank you!
On testing my app with tvOS 18, I have noticed the Siri Remote back button no longer provides system-provided behavior when interacting with tab bar controller pages. Instead of moving focus back to the tab bar when pressed, the back button will close the app, as if the Home button was pressed. This occurs both on device and in the Simulator.
Create tvOS project with a tab bar controller.
Create pages/tabs which contain focusable items (ie. buttons)
Scroll down to any focusable item (ie. a button or UICollectionView cell)
Hit the Siri Remote back button. See expect behavior below:
Expected behavior: System-provided behavior should move focus back to the tab bar at the top of the screen.
Actual results: App is closed and user is taken back to the Home Screen.
Has anyone else noticed this behavior?
I've encountered a potential bug where a TextField connected to an optional value (not a string) works as expected when bound to a @State property, but won't update a @Binding property.
Here is some example code
import SwiftUI
struct ContentView: View
{
@Binding var boundValue: Double?
@State private var stateValue: Double? = 55
var body: some View
{
TextField("Bound value", value: $boundValue, format: .number)
Text("\(boundValue ?? .nan)")
TextField("State value", value: $stateValue, format: .number)
Text("\(stateValue ?? .nan)")
}
}
#Preview
{
ContentView(boundValue: .constant(42.00))
}
It's as though the optional value stored externally is preventing the value updating. Can anyone confirm whether this is intentional, or a bug?
This is in Xcode 26b6, on macOS Tahoe 26b8, but from this query it looks like the problem has existed for years.
Topic:
UI Frameworks
SubTopic:
SwiftUI
I’m relatively new to SwiftUI, so I’ve got a pretty basic question here. In my watchOS app, I’m using ShareLink to share a string of text to the Mail and Messages apps. Mail shows up in the ShareLink sheet just fine, but Messages doesn’t appear.
What’s odd is that when I run the app in Xcode’s preview or in the Simulator, Messages does show up as a sharing option… So now I’m wondering if this is just a quirk with my device or if Apple doesn’t actually support sharing text to Messages from third-party watchOS apps yet? I know some Apple Watch apps (like Contacts) do support sending text/files to Messages, so I’m curious if anyone’s had a similar experience or knows more about this.
Any insights would be super helpful!
After upgrading to MacOS Sequoia and Xcode 16 my app was behaving oddly. While running the application from Xcode, the app appears to save data, but running the app again from Xcode, the data is not there. If I open the app on the iPhone, run it and create data, the data persists even after I kill the app from the app switcher.
I went many rounds through my code and found nothing that helped. I finally ran the sample app that appears when you begin a new project and that is behaving the same way. There are errors thrown.
error: the replacement path doesn't exist: "/var/folders/qv/m7sk8kcd3713j3l4bg8wt1lw0000gn/T/swift-generated-sources/@_swiftmacro_13SwiftDataTest11ContentViewV5items33_BCE1062261466603F5F86A688789BF68LL5QueryfMa.swift"
error: the replacement path doesn't exist: "/var/folders/qv/m7sk8kcd3713j3l4bg8wt1lw0000gn/T/swift-generated-sources/@_swiftmacro_13SwiftDataTest11ContentViewV5items33_BCE1062261466603F5F86A688789BF68LL5QueryfMa.swift"
error: the replacement path doesn't exist: "/var/folders/qv/m7sk8kcd3713j3l4bg8wt1lw0000gn/T/swift-generated-sources/@_swiftmacro_13SwiftDataTest11ContentViewV5items33_BCE1062261466603F5F86A688789BF68LL5QueryfMa.swift"
I am using a LayzVStack embedded into a ScrollView. The list items are fetched from a core data store by using a @FetchResult or I tested it also with the new @Query command coming with SwiftData.
The list has one hundred items 1, 2, 3, ..., 100.
The user scrolled the ScrollView so that items 50, 51, ... 60 are visible on screen.
Now new data will be fetched from the server and updates the CoreData or SwiftData model. When I add new items to the end of the list (e.g 101, 102, 103, ...) then the ScrollView is keeping its position.
Opposite to this when I add new items to the top (0, -1, -2, -3, ...) then the ScrollView scrolls down.
Is there a way with the new SwiftData and SwiftUI ScrollView modifiers to update my list model without scrolling like with UIKit where you can query and set the scroll offset pixel wise?
Hi All
I faced up with strange issue in my app.
Everything works in iOS 18.0 and lower.
But after install iOS 18.1 same app from App Store crashes every time with error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Storyboard (<UIStoryboard: 0x11f6287a0>) doesn't contain a view controller with identifier 'MKCPinEntryViewControllerIdentifier''
Interesting that this view controller exist in the Storyboard.
First call in app:
dispatch_async(dispatch_get_main_queue(), ^{
//No authentication, needs login view controller popped.
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
PinEntryViewController *pinViewController = [storyboard instantiateViewControllerWithIdentifier:@"PinEntryViewControllerIdentifier"];
pinViewController.delegate = self;
pinViewController.entryType = PinEntryTypeEnter;
[self.presentationContext presentViewController:pinViewController animated:YES completion:nil];
});
works good.
But second call in other place after 5 seconds:
dispatch_async(dispatch_get_main_queue(), ^{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
PinEntryViewController *pinViewController = [storyboard instantiateViewControllerWithIdentifier:@"PinEntryViewControllerIdentifier"];
pinViewController.delegate = self;
[self.presentationContext presentViewController:pinViewController animated:YES completion:nil];
});
crash the app with
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Storyboard (<UIStoryboard: 0x11f6287a0>) doesn't contain a view controller with identifier 'MKCPinEntryViewControllerIdentifier''
*** First throw call stack:
(0x1841b47cc 0x1814872e4 0x186d9c140 0x1063d692c 0x10301ec08 0x104370a30 0x10437271c 0x104382de8 0x1043829a4 0x184188204 0x184185440 0x184184830 0x1d01641c4 0x186ceaeb0 0x186d995b4 0x10667fe3c 0x1a9b72ec8)
libc++abi: terminating due to uncaught exception of type NSException
And issue not only with this view controller.
issue with all in that storyboard.
At start up instantiateViewControllerWithIdentifier works good with all view controllers identifiers. But on second call in other places in the app - all crash with same error
Reproduce in real device with iOS18.1 only. Simulators and devices with iOS 18.0 works well.
Could someone help me, what's wrong with the app?
I've been encountering significant issues with button responsiveness across my entire SwiftUI application after upgrading to iOS 18. While everything worked as expected on iOS 17, buttons across various views now sometimes fail to respond to initial taps and require a long press to trigger actions.
Here is a sample of a button within a toolbar, similar issues are occurring with other buttons throughout the app:
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Button(action: {
DispatchQueue.main.async {
navigationCoordinator.pushScreen(.account)
}
}) {
Image("User")
.resizable()
.scaledToFit()
.frame(width: 24.5, height: 24.5)
}
}
}
Expected Behavior: All buttons in the application should respond to a simple tap without requiring additional user effort, maintaining consistency with their behavior on iOS 17.
Actual Behavior: On iOS 18, the responsiveness of buttons throughout the application is inconsistent; sometimes they react to a simple tap, and other times they only respond to a long press. This erratic behavior disrupts the user experience and hinders basic app functionality.
I am looking to understand whether this is a widespread issue with the new OS version and if there are any fixes or patches anticipated from Apple. Thank you for your assistance!
Topic:
UI Frameworks
SubTopic:
SwiftUI
My iOS (iPhone/iPad/Mac Catalyst) app has a relatively complex authentication flow, primarily required due to it being an API client. Several of my views have .task modifiers that begin executing code when the views are created.
After moving to iOS 18 and Xcode 16, when running in the Simulator, I began noticing my workflow was breaking as views were being created out of sequence... but not by me 🤯
Here is an example stack when I place a breakpoint inside of this view's .task.
From my logging (and this stack) I can verify I am not creating this view.
This view has no preview associated with it, and there are no previews up the view hierarchy from it either.
This happens in the Simulator only
The only clue I have to go on is this line of text which is present at the top of what looks like ASM when I click on the (5) line in the stack above.
SwiftUI`(1) await resume partial function for dispatch thunk of static SwiftUI.PreviewModifier.makeSharedContext() async throws -> τ_0_0.Context:
If this (or any hierarchical view) used Previews, I'd remove them to see if it had an effect, but they don't! I'm at a loss on what to do here...
Input issues occur in the textField while using a bilingual keyboard (Korean and English).
System settings:
Keyboard: Bilingual (Korean & English)
Project environment:
Xcode >= 15.4 & iOS >= 18.0
Base localization: Korean
// UITextField settings:
textField.keyboardType = .decimalPad // or .phonePad
self.textField.addTarget(self, action: #selector(self.textFieldEditingChanged), for: .editingChanged)
@objc
func textFieldEditingChanged() {
self.textField.text = "\(self.textField.text!)-"
}
/*
Input: 123456
Expected: 1-2-3-4-5-6-
Result: 11111123456-
*/
The issue occurs when modifying the text of the textField in the editingChanged event.
In the above code, a hyphen is appended to the input with each character.
When typing 123456, the expected result is:
Input: 1 → Result: 1-
Input: 2 → Result: 1-2-
…
Input: 6 → Result: 1-2-3-4-5-6-
However, the actual result is 11111123456-.
Another example:
@objc
func textFieldEditingChanged() {
print("before", self.textField.text!)
self.textField.text = self.textField.text?.replacingOccurrences(of: "0", with: "1")
print("after", self.textField.text!)
}
When inputting 0 1 0 sequentially, the output is:
before 0 after 1
before 01 after 11
before 010 after 111
The value of "after" matches expectations,
but the "before" value reverts to 0 on the next input, even though it appears as 1 on the UI.
When the bilingual keyboard option is turned off or the base localization is set to something other than Korea, the issue does not occur.
Could you provide information on whether this issue will be resolved in the next iOS version, or if there is a workaround?
After updating iOS, my Cordova app behaves incorrectly after receiving a voip push.
When a push notification is received, my application launches CallKit, displays the Native Dialer screen and starts other necessary services.
Until 17.5.1 (possibly 17.5) everything worked correctly. All services and sockets were established/ connected and working. After updating iOS to 17.5, the application crashes, and while voice connection is established the app is no longer active. Xcode logs have these error messages:
Invalidating grant <invalid NS/CF object> failed
Type: Error | Timestamp: 2024-06-20 13:27:44.719601+02:00 | Process: MyApp | Library: WebKit | Subsystem: com.apple.WebKit | Category: ProcessCapabilities | TID: 0x3a4929
Invalidating grant <invalid NS/CF object> failed
Type: Error | Timestamp: 2024-06-20 13:27:44.732219+02:00 | Process: MyApp | Library: WebKit | Subsystem: com.apple.WebKit | Category: ProcessCapabilities | TID: 0x3a4929
Invalidating grant <invalid NS/CF object> failed
Type: Error | Timestamp: 2024-06-20 13:27:44.733996+02:00 | Process: MyApp | Library: WebKit | Subsystem: com.apple.WebKit | Category: ProcessCapabilities | TID: 0x3a4929
I am using:
Cordova iOS: 6.2
iOS 17.5.1
Can anyone please help?
Please has anyone found a workaround for duplicate back buttons appearing on the toolbar of a ContentView launched from a DocumentGroup?
The problem occurs with Xcode 14.0 running a basic DocumentGroup App on iOS 16.0.
To reproduce, simply build a new project using the "Document App" template. Build and run in the iOS/iPadOS simulator or on an iOS/iPadOS device.
Two back buttons appear. Only one functions. I've not found a way to eliminate the dud.
This problem has occurred throughout the Xcode 14.0 beta program.
Hi, we are developing a cross-platform library for creating desktop applications in C++: https://github.com/aseprite/laf
For this reason, in macOS, we cannot rely on the default NSApplication.run() event loop, so we decided to implement our custom event loop using the nextEventMatchingMask method.
Then, when a window is in fullscreen mode, for some reason the window stops receiving mouseMove events when the mouse pointer enters an area at the top of the window.
You can see this issue in action by trying the following example project:
https://github.com/martincapello/custom-event-loop-issue
This project just opens one window and uses a custom event loop, it displays the current mouse position at every mouseMove event received, and when the aforementioned area is entered it suddenly stops updating.
There is also a video showing how to reproduce it.
I was able to see that when the position stops updating, we still receive mouseMove events, but for a different window, a borderless window that is added to the NSApplication.windows collection when switching to fullscreen, and which seems to be taken the mouseMove events before reaching the main window.
Also, this issue doesn't happen when using the default NSApplication.run method, despite the borderless windows being added as well.
Hello !
Since iOS/iPadOS 18 there is a new switch transition between tabs in UITabBarController where is a little zoom of the selected UIViewController.
At first, I thought that was a bug but I found the same animation on the Apple's apps (like music, shortcuts...)
On my app, this animation produce a little flash/blink white before zooming, it's not smooth like on Apple's apps.
I searched on documentation but I didn't found any topics about how to disable it or handled it better.
Is this possible to disabled it ?
My app displays some text that should appear the same regardless of the container view or window size, i.e. it should grow and shrink with the container view or window.
On iOS there is UILabel.adjustsFontSizeToFitWidth but I couldn't find any equivalent API on macOS. On the internet some people suggest to iteratively set a smaller font size until the text fits the available space, but I thought there must be a more efficient solution. How does UILabel.adjustsFontSizeToFitWidth do it?
My expectation was that setting a font's size to a fraction of the window width or height would do the trick, but when resizing the window I can see a slightly different portion of it.
class ViewController: NSViewController {
override func loadView() {
view = MyView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
NSLayoutConstraint.activate([view.widthAnchor.constraint(equalTo: view.heightAnchor, multiplier: 3), view.heightAnchor.constraint(greaterThanOrEqualToConstant: 100)])
}
}
class MyView: NSView {
let textField = NSTextField(labelWithString: String(repeating: "a b c d e f g h i j k l m n o p q r s t u v w x y z ", count: 2))
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
textField.translatesAutoresizingMaskIntoConstraints = false
textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
addSubview(textField)
NSLayoutConstraint.activate([textField.topAnchor.constraint(equalTo: topAnchor), textField.leadingAnchor.constraint(equalTo: leadingAnchor), textField.trailingAnchor.constraint(equalTo: trailingAnchor)])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func resize(withOldSuperviewSize oldSize: NSSize) {
// textField.font = .systemFont(ofSize: frame.width * 0.05)
textField.font = .systemFont(ofSize: frame.height * 0.1)
}
}
I have a custom document-based iOS app that also runs on macOS. After implementing -activityItemsConfiguration to enable sharing from the context menu, I found that the app crashes on macOS when selecting Share… from the context menu and then selecting Save (i.e. Save to Files under iOS). This problem does not occur on iOS, which behaves correctly.
- (id<UIActivityItemsConfigurationReading>)activityItemsConfiguration {
NSItemProvider * provider = [[NSItemProvider alloc] initWithContentsOfURL:self.document.presentedItemURL];
UIActivityItemsConfiguration * configuration = [UIActivityItemsConfiguration activityItemsConfigurationWithItemProviders:@[ provider ]];
// *** crashes with com.apple.share.System.SaveToFiles
return configuration;
}
Additionally, I found that to even reach this crash, the workaround implemented in the NSItemProvider (FBxxx) category of the sample project is needed. Without this, the app will crash much earlier, due to SHKItemIsPDF() erroneously invoking -pathExtension on an NSItemProvider. This appears to be a second bug in Apple’s private ShareKit framework.
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
@implementation NSItemProvider (FBxxx)
// *** SHKItemIsPDF() invokes -pathExtension on an NSItemProvider (when running under macOS, anyway) -> crash
- (NSString *)pathExtension {
return self.registeredContentTypes.firstObject.preferredFilenameExtension;
}
@end
Again, this all works fine on iOS (17.5) but crashes when the exact same app build is running on macOS (14.5).
I believe these bugs are Apple's. Any idea how to avoid the crash? Is there a way to disable the "Save to Files" option in the sharing popup?
I filed FB13819800 with a sample project that demonstrates the crash on macOS. I was going to file a TSI to get this resolved, but I see that DTS is not responding to tech support incidents until after WWDC.
Topic:
UI Frameworks
SubTopic:
UIKit