My swift app has several places where it updates data stored with SwiftData. In each place I have to remember to add function doSomethingWithTheUpdatedData().
I would like my app to be reactive and call doSomethingWithTheUpdatedData() from a single place opposed to be scattered throughout my app. How to accomplish this?
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
At 11:37 in this video - https://developer.apple.com/videos/play/wwdc2021/10123/ - Nolan instantiates MyModel() in swiftui view file. And then at 12:02 he just uses MyModel from extension.
I have the exact same code and when I try to build my project, it fails with error that MyModel() could not be found.
I shared my MyModel.swift file between extension target and main app. Now it builds. However, it seems there are two separate instances of MyModel.
What is proper way for DeviceActivityMonitor extension to pass data to main app? I simply want to increment counter from extension every minute and let the main app to know that.
Or even better, - is there a way to use SwiftData from Device Activity Monitor extension?
I took CKShare with Zone example - https://github.com/apple/sample-cloudkit-sharing
Modified it a little bit so code looks like this:
struct ResourceView: View {
@State private var showingShare: Bool = false
@State private var shareView: CloudSharingView?
...
var body: some View {
HStack {
Button(action: {
Task {
let (share,container) = try! await shareConfiguration()
shareView = CloudSharingView(container: container, share: share)
showingShare = true
}
}) {
Label("Share", systemImage: "circle")
}
...
.sheet(isPresented: $showingShare) {
if let shareView = shareView {
shareView
} else {
Text("No sheet to show")
}
}
And the first time I click on Share button I am getting "No sheet to show" despite showingShare boolean being set after shareView variable. Presumably because shareView is nil.
The second time I click on Share button it shows the sharing view.
Topic:
UI Frameworks
SubTopic:
SwiftUI
When I try to install my app via USB cable on my child's iPhone 13 device I see following error in Xcode:
Installation on this device is prohibited by ManagedConfiguration
If I go to VPN & Device Management, I don't see anything. This is my Child's iphone so it is not like it is enrolled in some kind of school or work MDM.
Developer mode is ON and I added device ID to Certificates, Identifiers & Profiles > Devices.
Domain: IXRemoteErrorDomain
Code: 9
Failure Reason: Unhandled error domain IXRemoteErrorDomain, code 9
User Info: {
FunctionName = "-[IXSRemoteInstaller initWithRemoteInstallOptions:xpcAssetStream:assetSize:error:]";
SourceFileLine = 149;
}```
Is it cellular network provider that has locked something? How to be sure about this?
Topic:
Developer Tools & Services
SubTopic:
Xcode
I am creating a macOS app with the following requirements:
Automatic Startup: After initial installation, the app should automatically start, even after the OS restarts.
Notarized Installation: The installation package (.pkg) should be notarized to avoid user have to make security exception.
In my current setup I’ve created a script, ci_scripts/ci_post_xcodebuild.sh, which uploads the package file $CI_APP_STORE_SIGNED_APP_PATH/<appName>.pkg to GitHub via Xcode Cloud. While I can successfully download the app, I’m encountering two main issues:
Notarization (I assume): I’m unsure how to get Xcode Cloud to notarize the .pkg file. Currently, upon opening the .pkg file for the first time, users have to go to System Settings > Privacy & Security to allow an exception for the package, after which installation proceeds successfully on second try. I’d like to automate the notarization process to eliminate this extra step.
Adding Additional Files to PKG installer: My current .pkg file only includes the app binary. I need to configure Xcode Cloud to include a postinstall script and a launchd daemon configuration file within the package. This would ensure that necessary files are set up on installation and that the app is properly registered as a launch daemon.
I have a SwiftData model where I need to customize behavior based on the value of a property (connectorType). Here’s a simplified version of my model:
@Model
public final class ConnectorModel {
public var connectorType: String
...
func doSomethingDifferentForEveryConnectorType() {
...
}
}
I’d like to implement doSomethingDifferentForEveryConnectorType in a way that allows the behavior to vary depending on connectorType, and I want to follow best practices for scalability and maintainability. I’ve come up with three potential solutions, each with pros and cons, and I’d love to hear your thoughts on which one makes the most sense or if there’s a better approach:
**Option 1: Use switch Statements
**
func doSomethingDifferentForEveryConnectorType() {
switch connectorType {
case "HTTP":
// HTTP-specific logic
case "WebSocket":
// WebSocket-specific logic
default:
// Fallback logic
}
}
Pros: Simple to implement and keeps the SwiftData model observable by SwiftUI without any additional wrapping.
Cons: If more behaviors or methods are added, the code could become messy and harder to maintain.
**Option 2: Use a Wrapper with Inheritance around swiftdata model
**
@Observable
class ParentConnector {
var connectorModel: ConnectorModel
init(connectorModel: ConnectorModel) {
self.connectorModel = connectorModel
}
func doSomethingDifferentForEveryConnectorType() {
fatalError("Not implemented")
}
}
@Observable
class HTTPConnector: ParentConnector {
override func doSomethingDifferentForEveryConnectorType() {
// HTTP-specific logic
}
}
Pros: Logic for each connector type is cleanly organized in subclasses, making it easy to extend and maintain.
Cons: Requires introducing additional observable classes, which could add unnecessary complexity.
**Option 3: Use a @Transient class that customizes behavior
**
protocol ConnectorProtocol {
func doSomethingDifferentForEveryConnectorType(connectorModel: ConnectorModel)
}
class HTTPConnectorImplementation: ConnectorProtocol {
func doSomethingDifferentForEveryConnectorType(connectorModel: ConnectorModel) {
// HTTP-specific logic
}
}
Then add this to the model:
@Model
public final class ConnectorModel {
public var connectorType: String
@Transient
public var connectorImplementation: ConnectorProtocol?
// Or alternatively from swiftui I could call myModel.connectorImplementation.doSomethingDifferentForEveryConnectorType() to avoid this wrapper
func doSomethingDifferentForEveryConnectorType() {
connectorImplementation?.doSomethingDifferentForEveryConnectorType(connectorModel: self)
}
}
Pros: Decouples model logic from connector-specific behavior. Avoids creating additional observable classes and allows for easy extension.
Cons: Requires explicitly passing the model to the protocol implementation, and setup for determining the correct implementation needs to be handled elsewhere.
My Questions
Which approach aligns best with SwiftData and SwiftUI best practices, especially for scalable and maintainable apps?
Are there better alternatives that I haven’t considered?
If Option 3 (protocol with dependency injection) is preferred, what’s the best way to a)manage the transient property 2) set the correct implementation and 3) pass reference to swiftdata model?
Thanks in advance for your advice!
I have two recordTypes in CloudKit: Author and Book. The Book records have their parent property set to an Author, enabling hierarchical record sharing (i.e., if an Author record is shared, the participant can see all books associated with that author in their shared database).
When syncing with CKSyncEngine, I was expecting handleFetchedRecordZoneChanges to deliver all Author records before their associated Book records. However, unless I’m missing something, the order appears to be random.
This randomness forces me to handle two codepaths in my app (opposed to just one) to replicate CloudKit references in my local persistency storage:
Book arrives before its Author → I store the Book but defer setting its parent reference until the corresponding Author arrives.
Author arrives before its Books → I can immediately set the parent reference when each Book arrives.
Is there a way to ensure that Author records always arrive before Book records when syncing with CKSyncEngine? Or is this behavior inherently unordered and I have to implement two codepaths?
I changed my application's name and bundle identifier from xcode.
I am able to publish this app to testflight (internal) successfully. However, when users of my app report crash and I try to open them from App Store Connect crash section I see following error in Xcode:
Xcode failed to locate iOS App with App Store Identifier "XXXXXXX418".
If I open in Xcode > Window > Organizer > Crashes I see following error:
Upload "YourAPP" to App Store Connect to begin receiving crash logs.
It seems that AppStore identifier at one point changed and xcode and appstore connect are out of sync. What solution is there?
When I try to promote schema to production, I get following error:
Cannot promote schema with empty type 'workspace', please delete the record type before attempting to migrate the schema again
However, in hierarchical root record sharing, I think it should be completely legit use case where there is empty root record (in my case workspace) to which other records reference through ->parent reference.
Am I missing something? Is this weird constraint imposed on CloudKit?
I’m building a cross-platform app targeting macOS, iPad, and iPhone. My app currently uses both 2-level and 3-level navigation workflows:
3-level navigation:
First level: Categories
Second level: List of items in the selected category
Third level: Detail view for a specific item
2-level navigation:
First level: Category
Second level: A singleton detail view (for example, StatusView). It does not have concept of List.
After watching a couple of WWDC videos about multi-platform navigation, I decided to go with NavigationSplitView.
However, on macOS, a 3-column NavigationSplitView felt a bit overwhelming to my eyes when the third column was empty—especially for the occasional 2-level navigation case. So I removed the third column and instead embedded a NavigationStack in the second column. According to the official Apple documentation, this is supported:
You can also embed a NavigationStack in a column.
The code with NavigationStack in NavigationSplitView works fine on macOS.
But on iPhone, for the same code I’m seeing unexpected behavior:
The first time I tap on the “Actions” category, it briefly shows the “Select an item” view, and then automatically pops back to the all-categories view.
If I tap the same "Actions" category again, it shows the list of actions correctly, and everything works fine until I terminate and relaunch the app.
Here is a minimal reproducible example:
import SwiftUI
struct StatusView: View {
var body: some View {
NavigationStack {
List {
Text("Heartbeat: OK")
Text("Connected to backend: OK")
}
}
}
}
struct ActionListView: View {
var body: some View {
NavigationStack {
List {
NavigationLink(value: "Action 1 value") {
Text("Action 1 label")
}
NavigationLink(value: "Action 2 value") {
Text("Action 2 label")
}
}
}
.navigationDestination(for: String.self) { action in
Text(action)
}
}
}
struct ContentView: View {
var body: some View {
NavigationSplitView {
List {
NavigationLink(value: "Actions") {
Text("Actions (3 level)")
}
NavigationLink(value: "Modes") {
Text("Modes (3 level)")
}
NavigationLink(value: "State") {
Text("Status (2 level)")
}
}
.navigationDestination(for: String.self) { category in
switch category {
case "Actions":
ActionListView()
case "Modes":
Text("Modes View")
case "State":
StatusView()
default:
Text("Unknown Category")
}
}
} detail: {
Text("Select an item")
}
}
}
Questions and considerations:
How can I prevent this unexpected automatic pop back to the root view on iPhone the first time I select a category?
Future-proofing for more than 3 level navigation: In the future, I may allow users to navigate beyond three levels (e.g., an item in one category can reference another item in a different category). Is it correct to assume that to support this with back navigation, I’d need to keep using NavigationStack inside NavigationSplitView?
Is embedding NavigationStack in a 2 column NavigationSplitView the only practical approach to handle mixed 2 and 3 navigation depth if I don't want the third column to be ever empty?
On macOS, NavigationStack alone doesn’t feel appropriate for sidebar-based navigation. Does it mean everyone on macOS pretty much always use NavigationSplitView?
Any advice or examples would be appreciated. Thanks!
Topic:
UI Frameworks
SubTopic:
SwiftUI
I have this code example that works perfectly on iOS. But on MacOS, the changes made in view presented by Navigation Stack gets reverted after I click on Back button.
import SwiftUI
import Observation
enum Route: Hashable {
case selection
}
let allSelectables: [String] = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"]
@Observable
class Model {
var items: Set<String> = [] // Use Set for unique selections
}
struct ContentView: View {
@State var model = Model()
var body: some View {
NavigationStack {
VStack {
Text("Selected: \(model.items.joined(separator: ", "))")
List {
NavigationLink(value: Route.selection) {
Text("Go to Selection (\(model.items.count))")
}
}
.navigationDestination(for: Route.self) { route in
switch route {
case .selection:
List(allSelectables, id: \.self, selection: $model.items) { item in
Text(item)
}
#if os(iOS)
.environment(\.editMode, .constant(.active)) // Enable multiple selection
#endif
.navigationTitle("Selected: \(model.items.joined(separator: ", "))")
}
}
}
}
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
I am trying to install my LaunchAgent (which is bundled as .app in .pkg file) with:
sudo installer -pkg ./XXX.pkg -target /
And I see following error:
2025-07-29 19:06:29-05 MacBook-Pro installd[764]: PackageKit: Skipping component "com.XXX.Agent" (1.0.0-1.0.0-*) because the version 1.0.0-21.0.0-* is already installed at /Users/user/Downloads/Xcode Cloud Artifacts/XXX-C0E61B13-3F49-42DF-81B3-1037BC34D11B/b1ac6a32-3236-417e-bd62-88de90fa700d/789d0aa2-5531-403c-bcab-e3de8d6b34ee/myAgent.app.
After installer command returns, I don't see any files from my .app bundle extracted on filesystem.
If I understand the error message properly, then installer checks if ANYWHERE on filesystem there already exists this app bundle. And if it exists, then do not extract another copy of bundle.
But why? And do I need to specify version in xcodebuild command?
Topic:
App Store Distribution & Marketing
SubTopic:
General