Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

Error Loading USDZ File in Vision Pro Application
Hi everyone, I'm working on a Vision Pro application and encountering an issue while trying to load a USDZ file. Here are the details: File Path: /Users/siddharthpatel/Library/Developer/CoreSimulator/Devices/31F10013-50B6-4CEF-9388-9094087FAEBF/data/Containers/Data/Application/EB260F0A-A84F-4E95-876D-08199D2A4998/Documents/hive1.usdz Code: do { try await modelEntityForCollider = ModelEntity(contentsOf: fileURL!) } catch { print("Error loading model: (error)") } Error: Thread 1: Fatal error: Failed to import entity from "/Users/siddharthpatel/Library/Developer/CoreSimulator/Devices/31F10013-50B6-4CEF-9388-9094087FAEBF/data/Containers/Data/ ... ve1.usdz" I've verified that the file path is correct and the USDZ file exists at the specified location. What could be causing this error and how can I resolve it? Thanks in advance for your help! Siddharth
0
0
3
4h
how to open a binary webloc file with swift
I'm trying to get the url out of a binary webloc file, but I'm getting the follow error: NSURLConnection finished with error - code -1002. error: The file “link.webloc” couldn’t be opened. Does anyone know how to read a binary webloc file with swift? func readFile() { if let path = Bundle.main.path(forResource: "link", ofType: "webloc") { print("path: \(path)") if let url = URL(string: path) { do { let data = try Data(contentsOf: url) let plist = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) print("plist") } catch { print("error: \(error.localizedDescription)") } } } } I made a git repo of the project if anyone want to try it out. https://github.com/syclonefx/ReadWeblocFile. I have 2 different webloc files the link.webloc is a binary webloc file and the link2.webloc is a text webloc file
0
0
34
11h
SwiftData migration error
CrashLog Distributor ID: com.apple.AppStore Hardware Model: iPhone15,3 Process: DeadLineTodo [5556] Path: /private/var/containers/Bundle/Application/348CC8D5-05FD-41DF-93A3-C15562EF4AA8/DeadLineTodo.app/DeadLineTodo Identifier: andy.DeadLineTodo Version: 2.4.0 (3) AppStoreTools: 15F31e AppVariant: 1:iPhone15,3:17 Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] Coalition: andy.DeadLineTodo [2089] Date/Time: 2024-06-08 19:13:53.6259 +0800 Launch Time: 2024-06-08 19:13:53.2839 +0800 OS Version: iPhone OS 17.5.1 (21F90) Release Type: User Baseband Version: 2.60.02 Report Version: 104 Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x0000000195a2d8c0 Termination Reason: SIGNAL 5 Trace/BPT trap: 5 Terminating Process: exc handler [5556] Triggered by Thread: 0 Thread 0 name: Thread 0 Crashed: 0 libswiftCore.dylib 0x0000000195a2d8c0 _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:144) 1 DeadLineTodo 0x0000000100dde700 DeadLineTodoApp.init() + 1140 (DeadLineTodoApp.swift:46) 2 DeadLineTodo 0x0000000100ddef30 protocol witness for App.init() in conformance DeadLineTodoApp + 28 (<compiler-generated>:0) 3 SwiftUI 0x000000019b2c84c0 static App.main() + 116 (App.swift:114) 4 DeadLineTodo 0x0000000100ddeec4 static DeadLineTodoApp.$main() + 40 (<compiler-generated>:0) 5 DeadLineTodo 0x0000000100ddef5c main + 12 (DeadLineTodoApp.swift:32) 6 dyld 0x00000001ba7d1e4c start + 2240 (dyldMain.cpp:1298) Thread 1: 0 libsystem_pthread.dylib 0x00000001f3fa40c4 start_wqthread + 0 (:-1) Thread 2: 0 libsystem_pthread.dylib 0x00000001f3fa40c4 start_wqthread + 0 (:-1) Thread 0 crashed with ARM Thread State (64-bit): x0: 0x8000000100f01ad0 x1: 0x0000000000000000 x2: 0x0000000000000000 x3: 0x00000003019e9bc0 x4: 0x0000000000000000 x5: 0x000000016f16f3e0 x6: 0x000000000000002e x7: 0x0000000000000000 x8: 0x0000000000000100 x9: 0x00000000000000ff x10: 0x0000000000001b80 x11: 0x00000000f3444870 x12: 0x00000000000007fb x13: 0x00000000000007fd x14: 0x00000000f364506f x15: 0x000000000000006f x16: 0x00000000f3444870 x17: 0x0000000000045000 x18: 0x0000000000000000 x19: 0x0000000100f01dba x20: 0x8000000100f01ad0 x21: 0x0000000000000000 x22: 0x000000000000000b x23: 0x0000000000000022 x24: 0x000000000000002e x25: 0x0000000100f01ac0 x26: 0xd000000000000025 x27: 0x0000000000000000 x28: 0x0000000000000000 fp: 0x000000016f16f5c0 lr: 0x0000000195a2d8c0 sp: 0x000000016f16f4f0 pc: 0x0000000195a2d8c0 cpsr: 0x60001000 esr: 0xf2000001 (Breakpoint) brk 1 Binary Images: 0x100c90000 - 0x100f0ffff DeadLineTodo arm64 <c16650393d4537299a08b798b8227d31> /private/var/containers/Bundle/Application/348CC8D5-05FD-41DF-93A3-C15562EF4AA8/DeadLineTodo.app/DeadLineTodo 0x101214000 - 0x10121ffff libobjc-trampolines.dylib arm64e <2e2c05f8377a30899ad91926d284dd03> /private/preboot/Cryptexes/OS/usr/lib/libobjc-trampolines.dylib 0x1959f4000 - 0x195f43fff libswiftCore.dylib arm64e <d9ad5cc1ca2c3f0a8091652b0df56d14> /usr/lib/swift/libswiftCore.dylib 0x19af1c000 - 0x19ccbafff SwiftUI arm64e <c1325fda9da239d2ab83a338b4d8a884> /System/Library/Frameworks/SwiftUI.framework/SwiftUI 0x1ba795000 - 0x1ba821ef7 dyld arm64e <71846eacee653697bf7d790b6a07dcdb> /usr/lib/dyld 0x1f3fa3000 - 0x1f3fafff3 libsystem_pthread.dylib arm64e <1196b6c3333d3450818ff3663484b8eb> /usr/lib/system/libsystem_pthread.dylib EOF DeadLineTodoApp.swift import SwiftUI import SwiftData typealias TodoData = TodoDataSchemaV8.TodoData typealias UserSetting = TodoDataSchemaV8.UserSetting enum TodoDataMigrationPlan: SchemaMigrationPlan { static var schemas: [VersionedSchema.Type] { [TodoDataSchemaV1.self, TodoDataSchemaV2.self, TodoDataSchemaV3.self, TodoDataSchemaV4.self, TodoDataSchemaV5.self, TodoDataSchemaV6.self, TodoDataSchemaV7.self, TodoDataSchemaV8.self] } static var stages: [MigrationStage]{ [migrationV1toV2, migrationV2toV3, migrationV3toV4, migrationV4toV5, migrationV5toV6, migrationV6toV7, migrationV7toV8] } static let migrationV1toV2 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV1.self, toVersion: TodoDataSchemaV2.self) static let migrationV2toV3 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV2.self, toVersion: TodoDataSchemaV3.self) static let migrationV3toV4 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV3.self, toVersion: TodoDataSchemaV4.self) static let migrationV4toV5 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV4.self, toVersion: TodoDataSchemaV5.self) static let migrationV5toV6 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV5.self, toVersion: TodoDataSchemaV6.self) static let migrationV6toV7 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV6.self, toVersion: TodoDataSchemaV7.self) static let migrationV7toV8 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV7.self, toVersion: TodoDataSchemaV8.self) } @main struct DeadLineTodoApp: App { let container: ModelContainer @StateObject var store = StoreKitManager() @State var updated: Bool = false init() { do { container = try ModelContainer( for: TodoData.self, UserSetting.self, migrationPlan: TodoDataMigrationPlan.self) } catch { print("初始化模型容器时发生错误:\(error)") fatalError("Failed to initialize model container.") } } var body: some Scene { WindowGroup { ContentView(updated: $updated) .environmentObject(store) } .modelContainer(container) } }
0
0
55
22h
SwiftData migration error
Distributor ID: com.apple.AppStore Hardware Model: iPhone15,3 Process: DeadLineTodo [5556] Path: /private/var/containers/Bundle/Application/348CC8D5-05FD-41DF-93A3-C15562EF4AA8/DeadLineTodo.app/DeadLineTodo Identifier: andy.DeadLineTodo Version: 2.4.0 (3) AppStoreTools: 15F31e AppVariant: 1:iPhone15,3:17 Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] Coalition: andy.DeadLineTodo [2089] Date/Time: 2024-06-08 19:13:53.6259 +0800 Launch Time: 2024-06-08 19:13:53.2839 +0800 OS Version: iPhone OS 17.5.1 (21F90) Release Type: User Baseband Version: 2.60.02 Report Version: 104 Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x0000000195a2d8c0 Termination Reason: SIGNAL 5 Trace/BPT trap: 5 Terminating Process: exc handler [5556] Triggered by Thread: 0 Thread 0 name: Thread 0 Crashed: 0 libswiftCore.dylib 0x0000000195a2d8c0 _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:144) 1 DeadLineTodo 0x0000000100dde700 DeadLineTodoApp.init() + 1140 (DeadLineTodoApp.swift:46) 2 DeadLineTodo 0x0000000100ddef30 protocol witness for App.init() in conformance DeadLineTodoApp + 28 (<compiler-generated>:0) 3 SwiftUI 0x000000019b2c84c0 static App.main() + 116 (App.swift:114) 4 DeadLineTodo 0x0000000100ddeec4 static DeadLineTodoApp.$main() + 40 (<compiler-generated>:0) 5 DeadLineTodo 0x0000000100ddef5c main + 12 (DeadLineTodoApp.swift:32) 6 dyld 0x00000001ba7d1e4c start + 2240 (dyldMain.cpp:1298) Thread 1: 0 libsystem_pthread.dylib 0x00000001f3fa40c4 start_wqthread + 0 (:-1) Thread 2: 0 libsystem_pthread.dylib 0x00000001f3fa40c4 start_wqthread + 0 (:-1) Thread 0 crashed with ARM Thread State (64-bit): x0: 0x8000000100f01ad0 x1: 0x0000000000000000 x2: 0x0000000000000000 x3: 0x00000003019e9bc0 x4: 0x0000000000000000 x5: 0x000000016f16f3e0 x6: 0x000000000000002e x7: 0x0000000000000000 x8: 0x0000000000000100 x9: 0x00000000000000ff x10: 0x0000000000001b80 x11: 0x00000000f3444870 x12: 0x00000000000007fb x13: 0x00000000000007fd x14: 0x00000000f364506f x15: 0x000000000000006f x16: 0x00000000f3444870 x17: 0x0000000000045000 x18: 0x0000000000000000 x19: 0x0000000100f01dba x20: 0x8000000100f01ad0 x21: 0x0000000000000000 x22: 0x000000000000000b x23: 0x0000000000000022 x24: 0x000000000000002e x25: 0x0000000100f01ac0 x26: 0xd000000000000025 x27: 0x0000000000000000 x28: 0x0000000000000000 fp: 0x000000016f16f5c0 lr: 0x0000000195a2d8c0 sp: 0x000000016f16f4f0 pc: 0x0000000195a2d8c0 cpsr: 0x60001000 esr: 0xf2000001 (Breakpoint) brk 1 Binary Images: 0x100c90000 - 0x100f0ffff DeadLineTodo arm64 <c16650393d4537299a08b798b8227d31> /private/var/containers/Bundle/Application/348CC8D5-05FD-41DF-93A3-C15562EF4AA8/DeadLineTodo.app/DeadLineTodo 0x101214000 - 0x10121ffff libobjc-trampolines.dylib arm64e <2e2c05f8377a30899ad91926d284dd03> /private/preboot/Cryptexes/OS/usr/lib/libobjc-trampolines.dylib 0x1959f4000 - 0x195f43fff libswiftCore.dylib arm64e <d9ad5cc1ca2c3f0a8091652b0df56d14> /usr/lib/swift/libswiftCore.dylib 0x19af1c000 - 0x19ccbafff SwiftUI arm64e <c1325fda9da239d2ab83a338b4d8a884> /System/Library/Frameworks/SwiftUI.framework/SwiftUI 0x1ba795000 - 0x1ba821ef7 dyld arm64e <71846eacee653697bf7d790b6a07dcdb> /usr/lib/dyld 0x1f3fa3000 - 0x1f3fafff3 libsystem_pthread.dylib arm64e <1196b6c3333d3450818ff3663484b8eb> /usr/lib/system/libsystem_pthread.dylib EOF DeadLineTodoApp.swift import SwiftData typealias TodoData = TodoDataSchemaV8.TodoData typealias UserSetting = TodoDataSchemaV8.UserSetting enum TodoDataMigrationPlan: SchemaMigrationPlan { static var schemas: [VersionedSchema.Type] { [TodoDataSchemaV1.self, TodoDataSchemaV2.self, TodoDataSchemaV3.self, TodoDataSchemaV4.self, TodoDataSchemaV5.self, TodoDataSchemaV6.self, TodoDataSchemaV7.self, TodoDataSchemaV8.self] } static var stages: [MigrationStage]{ [migrationV1toV2, migrationV2toV3, migrationV3toV4, migrationV4toV5, migrationV5toV6, migrationV6toV7, migrationV7toV8] } static let migrationV1toV2 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV1.self, toVersion: TodoDataSchemaV2.self) static let migrationV2toV3 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV2.self, toVersion: TodoDataSchemaV3.self) static let migrationV3toV4 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV3.self, toVersion: TodoDataSchemaV4.self) static let migrationV4toV5 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV4.self, toVersion: TodoDataSchemaV5.self) static let migrationV5toV6 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV5.self, toVersion: TodoDataSchemaV6.self) static let migrationV6toV7 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV6.self, toVersion: TodoDataSchemaV7.self) static let migrationV7toV8 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV7.self, toVersion: TodoDataSchemaV8.self) } @main struct DeadLineTodoApp: App { let container: ModelContainer @StateObject var store = StoreKitManager() @State var updated: Bool = false init() { do { container = try ModelContainer( for: TodoData.self, UserSetting.self, migrationPlan: TodoDataMigrationPlan.self) } catch { fatalError("Failed to initialize model container.") } } var body: some Scene { WindowGroup { ContentView(updated: $updated) .environmentObject(store) } .modelContainer(container) } }
0
0
61
23h
Appending an item to an optional array within a struct
Hello All, some background information first. I have the following struct: Struct Category: Identifiable, Codeable, Hashable { var id: UUID var name: String var subCategory: [Category]? } var categories: [Category] There is no limit how many levels deep the subcategory can be. The user is essentially creating a hierarchical data filing system. Given that the number of subCategory levels is unlimited, I am recursing over the subcategories to find the correct level at which to insert the newCategory. The recursive function to add category is declared as: func recursiveAddCategory(newCategory: Category, subCategoryOf: inout [Category]?) you will note that I am trying to pass the subCategory as a reference (using inout), so that I can add to the original and the function is called as recursiveAddCategory(newCategory, &categories.subCategory!) the actual append statement within the recursiveAddCategory function is: categories.subCategory?.append(newCategory) I am encountering no errors but also find that the newCategory is not being added to the categories array. Any help or guidance appreciated. Thanks
0
0
28
1d
SwiftData fatal error: Failed to locate relationship for StringCodingKey
I'm experiencing a new error in SwiftData since updating to Xcode 16/iOS 17 DB1. When passing in a model (Student) to a view and then displaying an array of Points using ForEach, I get the following fatal error: SwiftData/ModelCoders.swift:2438: Fatal error: Failed to locate relationship for StringCodingKey(stringValue: "group", intValue: nil) on Entity - name: Point superentity: subentities: storedProperties: CompositeAttribute - name: type, options: [], valueType: PointType, defaultValue: nil Properties: Attribute - name: type, options: [], valueType: String, defaultValue: nil, hashModifier: nil Relationship - name: outcome, options: [], valueType: Outcome, destination: Outcome, inverseName: nil, inverseKeypath: nil CompositeAttribute - name: proficiency, options: [], valueType: Proficiency, defaultValue: nil Properties: Attribute - name: proficiency, options: [], valueType: String, defaultValue: nil, hashModifier: nil Attribute - name: date, options: [], valueType: Date, defaultValue: nil, hashModifier: nil Attribute - name: note, options: [], valueType: String, defaultValue: nil, hashModifier: nil Relationship - name: student, options: [], valueType: Optional<Student>, destination: Student, inverseName: points, inverseKeypath: Optional(\Student.points) Attribute - name: group, options: [], valueType: Array<PersistentIdentifier>, defaultValue: [], hashModifier: nil inheritedProperties: uniquenessConstraints: indices: Xcode flags this line of the macro-generated getter of the outcome property on Point: @storageRestrictions(accesses: _$backingData, initializes: _outcome) init(initialValue) { _$backingData.setValue(forKey: \.outcome, to: initialValue) _outcome = _SwiftDataNoType() } get { _$observationRegistrar.access(self, keyPath: \.outcome) return self.getValue(forKey: \.outcome) // Fatal error: Failed to locate relationship for StringCodingKey... } set { _$observationRegistrar.withMutation(of: self, keyPath: \.outcome) { self.setValue(forKey: \.outcome, to: newValue) } } This worked just fine in iOS 17. Here's a snippet of the Student implementation: @Model class Student: Identifiable, Comparable { var name: String var number: Int @Relationship(deleteRule: .cascade, inverse: \Point.student) var points: [Point] @Relationship(deleteRule: .cascade, inverse: \Mark.student) var marks: [Mark] @Relationship(deleteRule: .nullify, inverse: \StudentGroup.students) var groups: [StudentGroup] = [] var archived: Bool } and the implementation of Point: @Model class Point: Identifiable, Comparable { var student: Student? var type: PointType var outcome: Outcome var proficiency: Proficiency var group: [Student.ID] = [] var date: Date var note: String } and finally the implementation for Outcome: @Model class Outcome: Identifiable, Comparable { var name: String var index: Int var rubric: Rubric? var proficiencies: [Proficiency] } I've tried adding a relationship in Outcome as an inverse of the outcomes property on Points (although this does not make sense in my implementation, which is why I initially did not set a relationship here) and the problem persisted. Any ideas what this error means and how I might go about fixing it?
0
0
60
1d
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
123
2d
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) } }
3
0
149
2d
Main actor-isolated property can not be reference from a Sendable closure
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.
0
0
83
3d
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
74
3d
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
70
3d
Swift Data - fail gracefully if file can't be opened
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
0
0
65
4d
Action Will Not Run The Second Time Method is called
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() } } }
1
0
67
4d
How to avoid Swift 6 concurrency warning from UIAccessibility.post()
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?
3
0
130
4d
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
143
4d
Approach to adoption of Swift Testing
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?
3
0
176
4d