Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Posts under Swift tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

SwiftData History Tombstone Data is Unusable
After watching the WWDC video on the new history tracking in SwiftData, I started to update my app with this functionality. Unfortunately it seems that the current API in the first beta of Xcode 16 is rather useless in regards to tombstone data. The docs state that it would be possible to get the data from the tombstone by using a keyPath, there is no API for this however. The only thing I can do is iterate over the values (of type any) without any key information, so I do not know which data is what. Am I missing something or did we get a half finished implementation? There also does not seem to be any info on this in the release notes.
1
0
18
19m
SwiftData crashes on insert (Swift 6, Xcode 16, macOS 15)
I'm trying to insert values into my SwiftData container but it crashes on insert context.insert(fhirObject) and the only error I get from Xcode is: @Transient private var _hkID: _SwiftDataNoType? // original-source-range: /Users/cyril/Documents/GitHub/MyApp/MyApp/HealthKit/FHIR/FHIRModels.swift:35:20-35:20 configured as follows: import SwiftData import SwiftUI @main struct MyApp: App { var container: ModelContainer init() { do { let config = ModelConfiguration(cloudKitDatabase: .private("iCloud.com.author.MyApp")) container = try ModelContainer(for: FHIRObservation.self, configurations: config) UserData.shared = UserData(modelContainer: container) } catch { fatalError("Failed to configure SwiftData container.") } } var body: some Scene { WindowGroup { ContentView() .environmentObject(UserData.shared) } .modelContainer(container) } } My UserData and DataStore are configured as follows: import SwiftUI import SwiftData import os /// `FHIRDataStore` is an actor responsible for updating the SwiftData db as needed on the background thread. private actor FHIRDataStore { let logger = Logger( subsystem: "com.author.MyApp.FHIRDataStore", category: "ModelIO") private let container: ModelContainer init(container: ModelContainer) { self.container = container } func update(newObservations: [FHIRObservationWrapper], deletedObservations: [UUID]) async throws { let context = ModelContext(container) // [FHIRObservationWrapper] -> [FHIRObservation] // let modelUpdates = newObservations.lazy.map { sample in // FHIRObservation(hkID: sample.hkID, fhirID: sample.fhirID, name: sample.name, status: sample.status, code: sample.code, value: sample.value, range: sample.range, lastUpdated: sample.lastUpdated) // } do { try context.transaction { for sample in newObservations { let fhirObject = FHIRObservation(hkID: sample.hkID, fhirID: sample.fhirID, name: sample.name, status: sample.status, code: sample.code, value: sample.value, range: sample.range, lastUpdated: sample.lastUpdated) // App crashes here context.insert(fhirObject) } // for obj in modelUpdates { // // } // try context.delete(model: FHIRObservation.self, where: #Predicate { sample in // deletedObservations.contains(sample.hkID!) // }) // try context.save() logger.debug("Database updated successfully with new and deleted observations.") } } catch { logger.debug("Catch me bro: \(error.localizedDescription)") } } } @MainActor public class UserData: ObservableObject { let userDataLogger = Logger( subsystem: "com.author.MyApp.UserData", category: "Model") public static var shared: UserData! // MARK: - Properties public lazy var healthKitManager = HKManager(withModel: self) let modelContainer: ModelContainer private var store: FHIRDataStore init(modelContainer: ModelContainer) { self.modelContainer = modelContainer self.store = FHIRDataStore(container: modelContainer) } // MARK: - Methods func updateObservations(newObservations: [FHIRObservationWrapper], deletedObservations: [UUID]) { Task { do { try await store.update(newObservations: newObservations, deletedObservations: deletedObservations) userDataLogger.debug("Observations updated successfully.") } catch { userDataLogger.error("Failed to update observations: \(error.localizedDescription)") } } } } My @Model is configured as follows: public struct FHIRObservationWrapper: Sendable { let hkID: UUID let fhirID: String var name: String var status: String var code: FHIRCodeableConcept var value: FHIRLabValueType var range: FHIRLabRange? var lastUpdated: Date? } @Model public final class FHIRObservation { let hkID: UUID? let fhirID: String? @Attribute(.allowsCloudEncryption) var name: String? @Attribute(.allowsCloudEncryption) var status: String? @Attribute(.allowsCloudEncryption) var code: FHIRCodeableConcept? @Attribute(.allowsCloudEncryption) var value: FHIRLabValueType? @Attribute(.allowsCloudEncryption) var range: FHIRLabRange? @Attribute(.allowsCloudEncryption) var lastUpdated: Date? init(hkID: UUID?, fhirID: String?, name: String? = nil, status: String? = nil, code: FHIRCodeableConcept? = nil, value: FHIRLabValueType? = nil, range: FHIRLabRange? = nil, lastUpdated: Date? = nil) { self.hkID = hkID self.fhirID = fhirID self.name = name self.status = status self.code = code self.value = value self.range = range self.lastUpdated = lastUpdated } } Any help would be greatly appreciated!
2
0
78
20h
SwiftUI app runs differently on hardware platforms
I have a simple SwiftUI app that has a picker, textfield and several buttons. It is using a Enum as a focus state for the various controls. When I compile and run it on Mac Studio desktop it works as expected: Picker has initial focus, Selection in Picker changes focus to TextField, Tab key moves through buttons; last button resets to Picker However when I run the exact same app on MacBook Pro (same version of MacOS, 14.5) it does not work at all as expected. Instead: Initial focus is set to TextField, Tab does not change the focus, Clicking on last button resets focus to TextField rather than Picker The content view code: enum FFocus: Hashable { case pkNames case btnAssign case tfValue case btn1 case btn2 case noFocus } struct PZParm: Identifiable { var id = 0 var name = "" } struct ContentView: View { @State var psel:Int = 0 @State var tfVal = "Testing" @FocusState var hwFocus:FFocus? var body: some View { VStack { Text("Hardware Test").font(.title2) PPDefView(bSel: $psel) .focused($hwFocus, equals: .pkNames) TextField("testing", text:$tfVal) .frame(width: 400) .focused($hwFocus, equals: .tfValue) HStack { Button("Button1", action: {}) .frame(width: 150) .focused($hwFocus, equals: .btn1) Button("Button2", action: { tfVal = "" hwFocus = .tfValue }) .frame(width: 150) .focused($hwFocus, equals: .btn2) Button("New", action: { tfVal = "" hwFocus = .pkNames }) .frame(width: 150) .focused($hwFocus, equals: .btnAssign) } } .padding() // handle picker change .onChange(of: psel, { if psel > 0 {hwFocus = .tfValue} }) .onAppear(perform: {hwFocus = .pkNames}) } } #Preview { ContentView() } struct PPDefView: View { @Binding var bSel:Int // test defs let pzparms:[PZParm] = [ PZParm.init(id:1, name:"Name1"), PZParm.init(id:2, name:"Name2") ] // var body:some View { Picker(selection: $bSel, label: Text("Puzzle Type")) { ForEach(pzparms) {Text($0.name)} }.frame(width: 250) } }
1
0
88
3h
CommandGroup, Xcode 16b1, and Swift 6
I suspect this will be a "wait for the next beta" item, but thought I'd throw it out here in case anyone knows of a workaround. Mac app compiling under Xcode 16 beta 1. Trying to get rid of all warning that would stop the adoption of Swift 6 -- Strict Concurrency Checking is set to Complete. I'm down to one warning before I can enable swift 6. SwiftUI.Commands Main actor-isolated static method '_makeCommands(content:inputs:)' cannot be used to satisfy nonisolated protocol requirement; this is an error in the Swift 6 language mode That's because I've added menu commands to the app. It's very easy to reproduce. import SwiftUI @main struct CommandApp: App { var body: some Scene { WindowGroup { ContentView() } .commands { HelpCommand() } } } struct HelpCommand: Commands { var body: some Commands { CommandGroup(replacing: .help) { Button("Help me") { // } } } } The suggested fix is telling me what change I should make ot _makeCommands. At least that is how I'm reading it.
0
0
78
1d
App crashed with NSInvalidUnarchiveOperationException when run from different target and scheme.
Hi, I'm trying to create a new target duplicated from the main target (cdx_ios) called cdx-ios-dev02. I also made a new scheme called cdx-ios-dev02 It can be built just fine however when I run it, it crashed and it throws this exception: *** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (cdx_ios.AuthObject) for key (root) because no class named "cdx_ios.AuthObject" was found; the class needs to be defined in source code or linked in from a library (ensure the class is part of the correct target). If the class was renamed, use setClassName:forClass: to add a class translation mapping to NSKeyedUnarchiver' This is the class: class AuthObject: NSObject, NSCoding { var accessT1: String = "" var t1Type: String = "bearer" var refreshT1: String = "" var expiresIn: Int = 0 var scope: String = "" var jti: String = "" init(accessT1: String = "", t1Type: String = "bearer", refreshT1: String = "", expiresIn: Int = 0, scope: String = "", jti: String = "") { self.accessT1 = accessT1 self.t1Type = t1Type self.refreshT1 = refreshT1 self.expiresIn = expiresIn self.scope = scope self.jti = jti } convenience init(dic: [String: Any]) { self.init() mapping(dic) } required convenience init(coder aDecoder: NSCoder) { let t1 = aDecoder.decodeObject(forKey: "accessT1") as? String ?? "" let t1Type = aDecoder.decodeObject(forKey: "t1Type") as? String ?? "" let refreshT1 = aDecoder.decodeObject(forKey: "refreshT1") as? String ?? "" let expiresIn = aDecoder.decodeInteger(forKey: "expiresIn") let scope = aDecoder.decodeObject(forKey: "scope") as? String ?? "" let jti = aDecoder.decodeObject(forKey: "jti") as? String ?? "" self.init( accessT1: t1, t1Type: t1Type, refreshT1: refreshT1, expiresIn: expiresIn, scope: scope, jti: jti ) } func mapping(_ dic: [String: Any]) { accessT1 = ParseUtil.dictionaryValue(dic, "access_token", "") t1Type = ParseUtil.dictionaryValue(dic, "token_type", "bearer") refreshT1 = ParseUtil.dictionaryValue(dic, "refresh_token", "") expiresIn = ParseUtil.dictionaryValue(dic, "expires_in", 0) scope = ParseUtil.dictionaryValue(dic, "scope", "") jti = ParseUtil.dictionaryValue(dic, "jti", "") } func encode(with nsCoder: NSCoder) { nsCoder.encode(accessT1, forKey: "accessT1") nsCoder.encode(t1Type, forKey: "t1Type") nsCoder.encode(refreshT1, forKey: "refreshT1") nsCoder.encode(expiresIn, forKey: "expiresIn") nsCoder.encode(scope, forKey: "scope") nsCoder.encode(jti, forKey: "jti") } } It worked fine on the original target, cdx-ios. Can anybody help me? Thank you.
2
0
59
1d
Are several Proximity and Beacon related libraries methods and properties deprectaed and now unusable in iOS 18 beta?
Hi, Please let me know iOS 18 beta have deprecated/ stopped support for which of the following: proximityUUID CLBeaconRegion (instancetype)initWithProximityUUID:(NSUUID *)proximityUUID identifier:(NSString *)identifier (void)startRangingBeaconsInRegion:(CLBeaconRegion *)region -startRangingBeaconsSatisfyingConstraint: , is this also deprecated in iOS 18 beta, since: CLBeaconIdentityConstraint is deprecated right? CLBeaconIdentityCondition is not supported in XCode 15.3. What should I do for this? Should I install XCode 16 beta? locationManager:didRangeBeacons:satisfyingConstraint: can we use it in iOS 18 beta, since, CLBeaconIdentityConstraint is deprecated? what is alternative startMonitoring(for:) is also deprecated in iOS 18 beta right? Also, can someone specify or create a documentation on how beaconing shall be monitored, ranged and locationManager delegate methods pertaining to beaconing to be used in iOS 18 beta?
1
0
62
1d
Offloading task from the cooperative thread pool
Hi, When using Swift Concurrency blocking tasks like file I/O, GPU work and networking can prevent forward moving progress and have the potential to exhaust the cooperative thread pool and under utilize the CPU. It's been recommended to offload these tasks from the cooperative thread pool. Is my understanding correct that the preferred way to do this is by creating async tasks via Dispatch or OperationQueue? And combining these with Continuations if a return value from the task is required? Or should I always be using Continuations in combination with Dispatch/OperationQueue? There are also Executors but the documentation seems a bit limited on how to use these. The new TaskExecutor is also only available on the latest beta's. My question is basically what is the recommend way to offload a task? Thanks!
0
0
55
2d
Swift 6 actor error in didReceiveRemoteNotification of UIApplicationDelegate
From Xcode 16.0 Beta I am getting the following error at didReceiveRemoteNotification of UIApplicationDelegate protocol: Non-sendable type '[AnyHashable : Any]' in parameter of the protocol requirement satisfied by main actor-isolated instance method 'application(_:didReceiveRemoteNotification:)' cannot cross actor boundary; this is an error in the Swift 6 language mode Generic struct 'Dictionary' does not conform to the 'Sendable' protocol (Swift.Dictionary) How can I fix this warning before moving to Swift 6 mode.
0
0
48
2d
Can I ignore safe area when resizing a window in macOS 15?
I am attempting to make a macOS app to show a large popup with no titlebar and a transparent background that spans the entire active display. Currently, I am attempting the last part, with the sizing. I used an example on the relevant developer documentation page. This is the code I am using in my App struct: @main struct MakeGoodChoicesApp: App { ... var body: some Scene { ... Window("Make Good Choices", id:"popup") { PopupWindowContentView() .ignoresSafeArea(.all) } .windowIdealPlacement {_, context in return WindowPlacement( x: context.defaultDisplay.bounds.minX, y: context.defaultDisplay.bounds.minY, width: context.defaultDisplay.bounds.width, height: context.defaultDisplay.bounds.height ) } } } When running my application and using some code to open the popup window, I get the following result: I would expect the window to expand past the safe area, but it seems as if macOS clamped the window's size down to inside the safe areas. I would appreciate any help, many thanks!
0
1
56
2d
Fix actor-isolated class is different from nonisolated subclass error
I'm trying to migrate my fairly large application to Swift Concurrency. I've have a class marked as @MainActor that sub-classes a 3rd party abstract class that is not migrated to Swift Concurrency. I get the following error: Main actor-isolated class 'MyClass' has different actor isolation from nonisolated superclass 'OtherAbstractClass'; this is an error in the Swift 6 language mode My class needs to be MainActor as it uses other code that is required to be on the MainActor. I can't see how to suppress this warning, I know as a guarantee that the abstract class will always be on the main thread so I need a way of telling the compiler that when I don't own the 3rd party code. import OtherAbstractModule @MainActor class MyClass: OtherAbstractClass { .... } How can I satisfy the compiler in this case?
1
0
111
2d
SwiftData Custom Datastore Docs and Implementation
I have watched the following WWDC 2024 sessions: What’s new in SwiftData Create a custom data store with SwiftData Platform State of the Union Now, I have an application that exposes a GraphQL API endpoint that's using PostgreSQL Server 16.3 database. Next, this API returns JSON to the client application (i.e. SwiftUI app). Furthermore, I have checked the current documentation and the above videos appear to be the best reference at this time. My proposed architecture looks like the following: SwiftUI <--> SwiftData <--> PostgreStoreConfiguration && PostgreStore TBD <--> GraphQL API <--> PostgreSQL Thus, I have the following questions: Are there plans to add common out-of-the-box data store implementations for PostgreSQL, Cassandra, Redis, and so on? Will it be possible to implement data stores built to use gRPC, GraphQL, REST, and others to name a few? Will there be more documentation on the actual creation of a custom data store because the current documentation provides a slim API reference? I look forward to your feedback regarding the SwiftData custom data stores.
1
0
121
3d
SIGABRT Signal 6 Abort trap
I got crash report for my mobile application private var _timedEvents: SynchronizedBarrier<[String: TimeInterval]> private var timedEvents: [String: TimeInterval] { get { _timedEvents.value } set { _timedEvents.value { $0 = newValue } } } func time(event: String) { let startTime = Date.now.timeIntervalSince1970 trackingQueue.async { [weak self, startTime, event] in guard let self else { return } var timedEvents = self.timedEvents timedEvents[event] = startTime self.timedEvents = timedEvents } } From the report, the crash is happening at _timedEvents.value { $0 = newValue } struct ReadWriteLock { private let concurentQueue: DispatchQueue init(label: String, qos: DispatchQoS = .utility) { let queue = DispatchQueue(label: label, qos: qos, attributes: .concurrent) self.init(queue: queue) } init(queue: DispatchQueue) { self.concurentQueue = queue } func read<T>(closure: () -> T) -> T { concurentQueue.sync { closure() } } func write<T>(closure: () throws -> T) rethrows -> T { try concurentQueue.sync(flags: .barrier) { try closure() } } } struct SynchronizedBarrier<Value> { private let lock: ReadWriteLock private var _value: Value init(_ value: Value, lock: ReadWriteLock = ReadWriteLock(queue: DispatchQueue(label: "com.example.SynchronizedBarrier", attributes: .concurrent))) { self.lock = lock self._value = value } var value: Value { lock.read { _value } } mutating func value<T>(execute task: (inout Value) throws -> T) rethrows -> T { try lock.write { try task(&_value) } } } What could be the reason for the crash? I have attached the crash report. Masked.crash
4
0
116
2d
Using Core Data with the Swift 6 language mode
I'm starting to work on updating my code for Swift 6. I have a number of pieces of code that look like this: private func updateModel() async throws { try await context.perform { [weak self] in // do some work } } After turning on strict concurrency checking, I get warnings on blocks like that saying "Sending 'self.context' risks causing data races; this is an error in the Swift 6 language mode." What's the best way for me to update this Core Data code to work with Swift 6?
2
0
191
2d
The DateFormatter is returning wrong date format 2024-04-23T7:52:49.352 AMZ, 2024-05-23T11:16:24.706 a.m.Z
import Foundation let formatter = DateFormatter() let displayLocalFormat = true or false let timeZone = UTC let dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" let currentDate = Date() formatter.locale = displayLocalFormat ? Locale.current : Locale(identifier: "en_US_POSIX") formatter.dateFormat = dateFormat formatter.timeZone = timeZone formatter.string(from: date) // This function returns date format 2024-05-23T11:16:24.706 a.m.Z
5
0
162
3d
SwiftData SchemaMigrationPlan and VersionedSchema not Sendable?
I've just tried to update a project that uses SwiftData to Swift 6 using Xcode 16 beta 1, and it's not working due to missing Sendable conformance on a couple of types (MigrationStage and Schema.Version): struct LocationsMigrationPlan: SchemaMigrationPlan { static let schemas: [VersionedSchema.Type] = [LocationsVersionedSchema.self] static let stages: [MigrationStage] = [] } struct LocationsVersionedSchema: VersionedSchema { static let models: [any PersistentModel.Type] = [ Location.self ] static let versionIdentifier = Schema.Version(1, 0, 0) } This code results in the following errors: error: static property 'stages' is not concurrency-safe because non-'Sendable' type '[MigrationStage]' may have shared mutable state static let stages: [MigrationStage] = [] ^ error: static property 'versionIdentifier' is not concurrency-safe because non-'Sendable' type 'Schema.Version' may have shared mutable state static let versionIdentifier = Schema.Version(1, 0, 0) ^ Am I missing something, or is this a bug in the current seed? I've filed this as FB13862584.
1
1
104
3d
How to use CMHighFrequencyHeartRateData to read the Heart rate data from CoreMotion framework
Hello, As per Apple Documentation Link for CoreMotion framework we can read high frequency heart rate using CMHighFrequencyHeartRateData but there is No way to set the type like heartRate and have a updateHandler to provide the heart rate data. But for Accelerometer data, CoreMotion framework can provide startAccelerometerUpdates(to:, withHandler:) and user can set update interval like accelerometerUpdateInterval using CMMotionManager. But There is no solution available for heartRate. If any solution is available to read heartRate using CMHighFrequencyHeartRateData it will be helpful for me. I know we can read the Heart Rate Data using HealthKit framework using HKAnchoredObjectQuery but the heart rate data is not consistent and startDate & endDate for heart rate data is also not consistent. We want heart rate very frequent like every second. Any help can be appreciated. Thanks in advance
1
0
69
4d