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

UI not dynamically updating from push notifications fetchdata function
Hi All, I really need your help, I have been racking my brain to work out why, after a push notification triggers a fetchdata function from the server, my new bookings dont dynamically update the counter against the booking types. print("Received remote notification: \(userInfo)") if let dataInfo = userInfo["data"] as? [String: Any], let jsonData = try? JSONSerialization.data(withJSONObject: dataInfo) { print("Processing data from notification...") DispatchQueue.main.async { self.eventsViewModel.updateFromPushNotification(data: jsonData) { result in completionHandler(result) } } } else { print("Failed to parse notification data") completionHandler(.noData) } } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Failed to register for remote notifications: \(error)") } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { print("Will present notification: \(notification.request.content.userInfo)") DispatchQueue.main.async { self.eventsViewModel.fetchData() } completionHandler([.banner, .badge, .sound]) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print("Did receive notification response: \(response.notification.request.content.userInfo)") let userInfo = response.notification.request.content.userInfo if let fetchNeeded = userInfo["fetchNeeded"] as? Bool, fetchNeeded { print("Initiating data fetch due to user interaction...") DispatchQueue.main.async { self.eventsViewModel.fetchData() } } completionHandler() } @Published var bookings: [AnyBooking] = [] @Published var newBookings: [AnyBooking] = [] @Published var calendarBookings: [String: [AnyBooking]] = [:] @Published var selectedBooking: AnyBooking? private var cancellables = Set<AnyCancellable>() private let calendarManager = CalendarManager.shared // Add calendarManager func fetchData() { guard let url = URL(string: "https://allsound.wisewms.uk/webhook_get") else { print("Invalid URL for webhook request") return } var request = URLRequest(url: url) request.httpMethod = "GET" let task = URLSession.shared.dataTask(with: request) { [weak self] (data, response, error) in guard let self = self else { return } if let error = error { print("Error fetching data: \(error.localizedDescription)") return } if let data = data, !data.isEmpty { if let newBookings = self.processBookings(data: data) { DispatchQueue.main.async { self.bookings = newBookings self.separateAndOrganizeBookings(bookings: newBookings) } } else { print("Failed to process bookings.") } } else { print("No data received from server.") } } task.resume() } @main struct AllSoundApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate @StateObject var eventsViewModel = EventsViewModel() @Environment(\.scenePhase) var scenePhase @AppStorage("selectedTheme") private var selectedTheme: Theme = .system var body: some Scene { WindowGroup { ContentView() .environmentObject(eventsViewModel) .environmentObject(appDelegate.navigationCoordinator) .preferredColorScheme(selectedTheme.colorScheme) .onChange(of: scenePhase) { oldPhase, newPhase in if newPhase == .active { eventsViewModel.fetchData() } } } } }
2
0
129
1w
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
119
1w
JSON Encoder Crashing
Hi For some of the user the JSON Encoder is giving crash while converting array of Models into the dictionary its not reproducible at our end. Below is the stack trace of the issue 2024-06-14_21-18-38.4054_-0500-90aad9908d4fb2c7b8e49ce4b3025fab79674e31.crash Please help with above crash how can we reproduce and what should be the solution for this. Thanks
1
0
143
1w
PHP doesn't show images in WKWebView
Since httpRequest body is ignored on WKWebView, I am trying to display a php page by fetching the data first, and displaying it. func fetchData() { URLSession.shared.dataTask(with: request) {(data, response, error) in guard let data, let url = request.url else { return } // pass the result to WKWebView }.resume() } import Foundation import SwiftUI import WebKit struct CustomWebView: UIViewRepresentable { var url: URL var data: Data func makeUIView(context: Context) -> UIView { return CustomUIWebView(url: url, data: data) } } class CustomUIWebView: UIView { let webView: WKWebView init(url: URL,data:Data) { let webConfiguration = WKWebViewConfiguration() webView = WKWebView(frame: .zero, configuration: webConfiguration) super.init(frame: .zero) webView.load(data, mimeType: "text/html", characterEncodingName: "utf-8", baseURL: url) addSubview(webView) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() webView.frame = bounds } The data contains the page that display several images, but it doesn't display any of the images in WKWebView. Test and other components (such as checkmark button) have no problem, only images do. Also, I confirmed it works fine on Safari. So what is the issue here? What am I doing wrong?
0
0
91
1w
How to determine that NWBrowser has finished?
I am using NWBrowser to detect SignalK servers on a network using the following Swift code: let browser = NWBrowser(for: .bonjourWithTXTRecord(type: "_http._tcp", domain: nil), using: NWParameters()) browser.browseResultsChangedHandler = { results, changes in print("Found \(results.count) results and \(changes.count) changes") } When this is run on a network with 5 devices then the output is often Found 5 results and 5 changes But, sometime it is: Found 2 results and 2 changes Found 5 results and 3 changes indicating that the browseResultsChangedHandler is being called more than once. So my question is how do I determine when the browsing process has finished (obviously without the knowledge that there are 5 devices)? The depreciated NetServiceBrowser had a delegate method (netServiceBrowser(_:didFind:moreComing:) but I can't see an equivalent for NWBrowser. The only method I can think of is to apply a short time out.
3
0
135
1w
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
127
1w
TipKit vs. Swift 6 + Concurrency
I'm trying to convert my project to use Swift 6 with Complete Concurrency in Xcode 16 beta 1. The project uses TipKit, but I'm getting compile errors when trying to use the TipKit Parameters feature. Here is an example of the type of error I'm seeing (Note that this code from https://developer.apple.com/documentation/tipkit/highlightingappfeatureswithtipkit): struct ParameterRuleTip: Tip { // Define the app state you want to track. @Parameter static var isLoggedIn: Bool = false Static property '$isLoggedIn' is not concurrency-safe because it is non-isolated global shared mutable state. Is there a new pattern for supporting TipKit Parameters in Swift 6 with Complete Concurrency enabled? There is no obvious suggestion for how to fix this. The latest WWDC 2024 TipKit doesn't appear to have any solution(s).
6
2
231
4d
How to set up multi platform efficiently
Hello, so I have a SwiftUI app that is relatively large, and it has multiple targets, one for each platform. but as I near App Store release I'm feeling very confused as to how to configure it. One app was rejected because the Mac target's name becomes the app which is different from App Store (Texty+ [App Store] vs Texty+ Mac [on target]). So I then just combined all the files into one target with a #if os(Mac... iOS) etc, but is that the proper way for multi platform app. I know there is like a Multiplatform target but that would require I restructure all the files and that always leads to issues in this near release app.
1
0
142
1w
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
124
1w
Is the issue of code-theft via decompilation or reverse engineering common for Swift iOS apps? And can I protect a small portion of my code?
I'm a new app developer and I've read through most relevant posts on this topic here and elsewhere. Many of the forum posts here are specific to Objective-C, or old enough to be considered outdated in the fast-moving world of computing. Many of the posts elsewhere are about protecting authentication secrets, which doesn't apply in my case, and a lot are by someone with a product to sell, which I've ignored. My app is 99.9% Swift and I'm not going to store any authentication secrets in the IPA. What I'd like to protect is the core mechanism of my product, which has to be included in the binary and is small (&lt; 10k lines). I want to make it so it's harder to steal the source code than it is to recreate my functionality from scratch, which is difficult even with the app in front of them. From what I gathered, Swift code compiled by Xcode is protected from reverse engineering / decompilation by the following: Symbolization of the app Native builds from Xcode destroys names of variable, functions, etc. Swift code is compiled in such a way that makes stealing harder than Objective-C This should make me feel better, but the threat-level is increasing with the availability of free, commercial-grade decompilers (e.g. Ghidra) and machine learning. The fact that iOS 18 supports a checkm8 (i.e. jailbreakable) device means that decrypting the IPA from memory is still trivial. Questions People talk about stealing authentication secrets via reverse-engineering, but is the same true for mechanisms (i.e. code)? How common is the issue of source-code stealing in iOS apps? Can machine learning be leveraged to make decompilation/reverse engineering easier? Will I get rejected by App Review for obfuscating a small portion of my code?
11
0
333
15h
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
189
1w
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
226
1w
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
2
167
2w
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.
3
0
157
1w
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?
4
0
161
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
128
2w
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
1
110
2w