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!
Post
Replies
Boosts
Views
Activity
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)
}
}
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.
I am working thru the issues of turning on Strict Concurrency Checking. I have a SwiftData application, and I am compressing images before saving them as data. My save function is pretty simple
private func save() {
ImageCompressor.compress(image: (frontImageSelected?.asUIImage())!, maxByte: 1_048_576) { image in
guard image != nil else {
print("Error compressing image")
return
}
if let greetingCard {
greetingCard.cardName = cardName
greetingCard.cardFront = image?.pngData()
greetingCard.cardManufacturer = cardManufacturer
greetingCard.cardURL = cardURL
greetingCard.eventType = eventType
} else {
let newGreetingCard = GreetingCard(cardName: cardName, cardFront: image?.pngData(), eventType: eventType, cardManufacturer: cardManufacturer, cardURL: cardURL)
modelContext.insert(newGreetingCard)
}
}
}
I compress the selected image, I had to change my ImageCompressor.compress closure to Sendable, but now every assignment above is flagging with the above warning. I define the greetingCard as var greetingCard: GreetingCard? in my view, since I can have it passed in for edit, or generated if new.
I also get the same warning on modelContext, which is defined as @Environment(\.modelContext) private var modelContext.
It's not clear to me how to address this warning. Any pointers would be helpful.
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?
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!
struct Preview: View {
private static let NAME = "Test"
@Query(filter: #Predicate<Item> { $0.name == Preview.NAME})
private var items: [Item]
var body: some View {
MyView(name: Preview.NAME, items: items)
}
}
Compile error occurs: key path cannot refer to static member 'NAME'
How can a (static) constant be referred in member closure?
Hello
By default if swiftData is unable to open a file on mac (due to it being the wrong format, or an old model) the app hard crashes (macOS 14.4.1) - is there a way to catch this problem and present a message to the user, rather than the app simply crashing
The whole way that swiftData opens files etc is very opaque so I'm not clear how we can wrap things in a nice way
Thanks
Richard
In my method moveSun() it successfully rotates and plays the sound the first time it is called. However, subsequent calls to the method only play the sound and do not execute the rotate action. Does anyone know what may be causing this? Here's the relevant code:
func moveSun()
{
print(sunMoving)
let rotateAction = SKAction.rotate(toAngle: 2 * CGFloat.pi, duration: 2)
let playGearSound = SKAction.playSoundFileNamed("spinningGear", waitForCompletion: true)
let rotateAndPlayGearSound = SKAction.group([rotateAction, playGearSound])
sun.run(rotateAndPlayGearSound, completion: { self.sunMoving = false; print("completed completion handler") })
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
for t in touches
{
self.touchDown(atPoint: t.location(in: self))
}
}
func touchDown(atPoint pos : CGPoint)
{
let touchedNodes = nodes(at: pos)
for touchedNode in touchedNodes
{
print("touchNode: \(String(describing: touchedNode.name))")
if touchedNode.name == "sun" && !sunMoving
{
sunMoving = true
moveSun()
}
}
}
I have the following var in an @Observable class:
var displayResult: String {
if let currentResult = currentResult, let decimalResult = Decimal(string: currentResult) {
let result = decimalResult.formatForDisplay()
UIAccessibility.post(notification: .announcement, argument: "Current result \(result)")
return result
} else {
return "0"
}
}
The UIAccessiblity.post gives me this warning:
Reference to static property 'announcement' is not concurrency-safe because it involves shared mutable state; this is an error in Swift 6
How can I avoid this?
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?
Currently Swift Testing has much less features than XCTest, so the adoption will be very slow from our side. Notable features we miss are UI tests, performance tests and attachments.
I did not want to create many issues in Swift Testing GitHub project as lots of these shortcoming are most probably tracked internally (I can see lots of references to radars in GitHub issues.)
So, my question is: Is it a good idea to wait with wider adoption or should we experiment with other tools like swift Benchmarks?
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
Why is "Go small with embedded Swift" still not available, despite the fact all the other WWDC24 Tuesday session videos are?
Hello,
I develop an HCE payment app.
In this app I can redirect users in Settings to set the default payment app
UIApplication.shared.open(URL(string: "App-prefs:General&path=CONTACTLESS_NFC")
But is it possible to know which app is selected or if my app is already set as default ?
I have a public swift function with the below declaration :
public func InternalMain (_ pNumOfArgs : Int32, _ pCmdlineArgs : UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>) -> Int32 {..}
I need this function as public because I need to invoke in from a different library. But the above declaration produces an error in my generated swift header i.e '-swift.h' file because 'UnsafeMutablePointer<UnsafeMutablePointer?>' type cannot be represented in the swift generated header.
Can someone help how do I get past this. This is a class independent function and I tried using the '@nonobj' to prevent this from getting in the generated header but it still gives an error.
When we pass some special words, NSString.getBytes does not crash even when we pass an invalid range.
It seems a bug.
The below code is an example.
func testNSStringGetBytes() {
let originalString: String = "あ"
let bufferSize = 256
var buffer = [UInt8](repeating: 0, count: bufferSize)
var usedLength = 0
// An invalid range is passed
let range = NSRange(location: 0, length: originalString.count + 1)
var remainingRange = NSRange()
(originalString as NSString)
.getBytes(
&buffer,
maxLength: bufferSize,
usedLength: &usedLength,
encoding: String.Encoding.utf8.rawValue,
options: [],
range: range,
remaining: &remainingRange
)
print("Used Length: \(usedLength)")
print("Buffer: \(buffer[0..<usedLength])")
if remainingRange.length > 0 {
print("Did not convert the whole string. Remaining range: \(remainingRange)")
} else {
print("Entire string was converted successfully.")
}
}
In app delegate I'm trying to load an array with strings from a plist. I print the plist it prints fine...
func loadTypesArray() {
guard let path = Bundle.main.path(forResource: "Types", ofType: "plist") else {return}
let url = URL(fileURLWithPath: path)
let data = try! Data(contentsOf: url)
guard let plist = try! PropertyListSerialization.propertyList(from: data, options: .mutableContainers, format: nil) as? [String] else {return}
print(plist)
typesArray = plist
// print(typesArray)
}
But when I try and access it from a different part of the app using let typesArray = AppDelegate().typesArray
the array I get is an empty array! any help?
I'm building a macOS target for my App (which also has some Obj-C code).
Building and running the app is fine but when I archive the app in XCode, the process / build fails with the following error
Type 'BOOL' (aka ;Int32') cannot be used as a boolean;test for '!=0' instead
It happens in a couple of places, one of the places being
private func getRootDirectory(createIfNotExists: Bool = true) throws -> URL {
return try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
}
where it complains that create: true is not acceptable and throws the above error.
If I comment out this line, the archive works successfully.
When i Cmd + click the definition of Filemanager.default.url , i get this
@available(macOS 10.6, *)
open func url(for directory: FileManager.SearchPathDirectory, in domain: FileManager.SearchPathDomainMask, appropriateFor url: URL?, create shouldCreate: BOOL) throws -> URL
This looks fishy since it it says create shouldCreate: BOOL whereas the documentation says it should be just Bool
func url(
for directory: FileManager.SearchPathDirectory,
in domain: FileManager.SearchPathDomainMask,
appropriateFor url: URL?,
create shouldCreate: Bool
) throws -> URL
My minimum deployment target is macOS 13.0
I'm quite stumped at this error - which happens only while archiving. Does anybody know why?
Is there possible to record audio during application in kill/terminate state?
I am working with application where I have to record microphone voice for some process so I can it during application in foreground and background state, I have no idea about application kill state.