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

Posts under Swift tag

200 Posts

Post

Replies

Boosts

Views

Activity

Programming Languages Resources
This topic area is about the programming languages themselves, not about any specific API or tool. If you have an API question, go to the top level and look for a subtopic for that API. If you have a question about Apple developer tools, start in the Developer Tools & Services topic. For Swift questions: If your question is about the SwiftUI framework, start in UI Frameworks > SwiftUI. If your question is specific to the Swift Playground app, ask over in Developer Tools & Services > Swift Playground If you’re interested in the Swift open source effort — that includes the evolution of the language, the open source tools and libraries, and Swift on non-Apple platforms — check out Swift Forums If your question is about the Swift language, that’s on topic for Programming Languages > Swift, but you might have more luck asking it in Swift Forums > Using Swift. General: Forums topic: Programming Languages Swift: Forums subtopic: Programming Languages > Swift Forums tags: Swift Developer > Swift website Swift Programming Language website The Swift Programming Language documentation Swift Forums website, and specifically Swift Forums > Using Swift Swift Package Index website Concurrency Resources, which covers Swift concurrency How to think properly about binding memory Swift Forums thread Other: Forums subtopic: Programming Languages > Generic Forums tags: Objective-C Programming with Objective-C archived documentation Objective-C Runtime documentation Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
0
0
1k
Oct ’25
SensorKit - didFetchResult never get called.
We tried to fetch the recorded PPG data using SensorKit with the following code, however the didFetchResult callback method is never called. let ppgReader = SRSensorReader(sensor: .photoplethysmogram) let request = SRFetchRequest() let nowDate = Date() let toDate = nowDate.addingTimeInterval(-25 * 60 * 60) let fromDate = toDate.addingTimeInterval(-24 * 60 * 60) request.from = SRAbsoluteTime.fromCFAbsoluteTime(_cf: fromDate.timeIntervalSinceReferenceDate) request.to = SRAbsoluteTime.fromCFAbsoluteTime(_cf: toDate.timeIntervalSinceReferenceDate) ppgReader.delegate = self; ppgReader.fetch(request) The delegate called the didComplete successfully: func sensorReader(_ reader: SRSensorReader, didCompleteFetch fetchRequest: SRFetchRequest) But never called the didFetchResult func sensorReader(_ reader: SRSensorReader, fetching fetchRequest: SRFetchRequest, didFetchResult result: SRFetchResult<AnyObject>) -> Bool Any ideas why ? (I am wearing the watch for couple days and ensure it has the data for the time period I am querying) One thing I notice is when Apple granted us the entitlement, it uses Uppercase for ECG and PPG, however the document use Lowercases in the plist https://developer.apple.com/documentation/sensorkit/srsensor/photoplethysmogram Dose it matter ?
0
0
7
44m
Cannot Accept CloudKit Share After First App Install
I have an iOS app (1Address) which allows users to share their address with family and friends using CloudKit Sharing. Users share their address record (CKRecord) via a share link/url which when tapped allows the receiving user to accept the share and have a persistent view into the sharing user's address record (CKShare). However, most users when they recieve a sharing link do not have the app installed yet, and so when a new receiving user taps the share link, it prompts them to download the app from the app store. After the new user downloads the app from the app store and opens the app, my understanding is that the system (iOS) will/should then vend to my app the previously tapped cloudKitShareMetadata (or share url), however, this metadata is not being vended by the system. This forces the user to re-tap the share link and leads to some users thinking the app doesn't work or not completing the sharing / onboarding flow. Is there a workaround or solve for this that doesn't require the user to tap the share link a second time? In my scene delegate I am implementing: func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {...} And also func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {...} And also: func windowScene(_ windowScene: UIWindowScene, userDidAcceptCloudKitShareWith cloudKitShareMetadata: CKShare.Metadata) {...} And: func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {...} Unfortunately, none of these are called or passed metadata on the initial app run after install. Only after the user goes back and taps a link again can they accept the share. This documentation: https://developer.apple.com/documentation/cloudkit/ckshare says that adding the CKSharingSupported key to your app's Info.plist file allows the system to launch your app when a user taps or clicks a share URL, but it does not clarify what should happen if your app is being installed for the first time. This seems to imply that the system is holding onto the share metadata and/or url, but for some reason it is not being vended to the app on first run. Open to any ideas here for how to fix and I also filed feedback: FB20934189.
1
1
40
9h
JavaScript/Swift Interoperability
I think that it would be helpful to have better interoperability between Swift and JavaScript. There are a lot of useful packages on NPM that don't have equivalents for Swift. It would be helpful if Apple provided easier ways to use NPM packages in a Swift project. Currently, the JavaScriptCore framework is missing many standard things used in many packages, like the fetch API. It would be helpful to be able to run sandboxed JavaScript code inside of a Swift app but allow access to specific domains, folders, etc., using a permissions system similar to Deno.
6
1
998
2d
iOS and Android
I currently have a iOS app live on the App Store but I also want to release it on Android, the whole code is in Swift so would that be possible or would I have to rewrite my whole apps code in a different coding language.
2
0
332
2d
Applescript run as a Quick Action errors out when run inside a Shortcut.
I have a Quick Action which flattens a PDF via Applescript. The code works extremely well--I right click in finder and the PDF is flattened, annotations are burned in, no other applications are opened, and the action completes in less than 2 seconds. Here is the Applescript code: I have a Shortcut which completes several operations on already-flattened PDFs. Presently 1) I run my Quick Action by right-clicking a PDF in Finder in order to flatten it, and 2) then right-click that save PDF in Finder to run my Shortcut on that now-flattened PDF. Ideally I'd like to add the Applescript code which flattens the PDF to the beginning of my Shortcut for the sake of convenience, and because sometimes I run my Shortcut having forgotten to flatten the PDF first. However I'm finding that the Applescript code, when placed into a Run Applescript action in Shortcuts, gives this error message: The exact same code when placed into a Run Applescript action in Automator and then run as a Quick Action by right-clicking the PDF in Finder, does not give an error and works perfectly. Does anybody have an explanation (and possible solution) for why this is the case?
2
0
72
3d
[iOS 26.2] Crash due to WKScriptMessageHandler delegate
The crash is specific to iOS 26.2 prior versions working fine. WKScriptMessageHandler delegate func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) Name attribute is accessible but WKScriptMessage body attribute causes crash The object seems to be not accessible(not in memory) self.webkit.configuration.userContentController.add(self, name: "sampleHandler") self.webkit.load(request) func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { print(message.name) // works print(message.body) // crashes }
3
1
487
3d
Content Filter Permission Prompt Not Appearing in TestFlight
I added a Content Filter to my app, and when running it in Xcode (Debug/Release), I get the expected permission prompt: "Would like to filter network content (Allow / Don't Allow)". However, when I install the app via TestFlight, this prompt doesn’t appear at all, and the feature doesn’t work. Is there a special configuration required for TestFlight? Has anyone encountered this issue before? Thanks!
9
1
476
3d
Errors with PerfPowerTelemetryClientRegistrationService and PPSClientDonation when running iOS application in Xcode
I've suddenly started seeing hundreds of the same block of four error messages (see attached image) when running my app on my iOS device through Xcode. I've tried Cleaning the Build folder, but I keep seeing these messages in the console but can't find anything about them. Phone is running iOS 26.1. Xcode is at 16.4. Mac is on Sequoia 15.5. The app is primarily a MapKit SwiftUI based application. Messages below: Connection error: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.PerfPowerTelemetryClientRegistrationService was invalidated: Connection init failed at lookup with error 159 - Sandbox restriction." UserInfo={NSDebugDescription=The connection to service named com.apple.PerfPowerTelemetryClientRegistrationService was invalidated: Connection init failed at lookup with error 159 - Sandbox restriction.} (+[PPSClientDonation isRegisteredSubsystem:category:]) Permission denied: Maps / SpringfieldUsage (+[PPSClientDonation sendEventWithIdentifier:payload:]) Invalid inputs: payload={ isSPR = 0; } CAMetalLayer ignoring invalid setDrawableSize width=0.000000 height=0.000000 I'm also seeing the following error messages: CoreUI: CUIThemeStore: No theme registered with id=0
2
3
178
3d
iOS Content Filter Permission Prompt Not Appearing in TestFlight and Not Working
I added a Content Filter to my app, and when running it in Xcode (Debug/Release), I get the expected permission prompt: "Would like to filter network content (Allow / Don't Allow)". However, when I install the app via TestFlight, this prompt doesn’t appear at all, and the feature doesn’t work. Is there a special configuration required for TestFlight? I already set the minimum deployment to be 17 for the extension and the app. Thanks!
3
0
121
3d
Library not loaded: @rpath/libswiftCompatibilitySpan.dylib – Building bundle target
I am building a bundle target for macOS 12 and later using Xcode. The bundle is not a standalone app, but a plug-in that is loaded by a host app. The code is written in Swift and uses the new Span API which is available in the OS-provided standard library in macOS 26 and backdeploys to macOS 10.14.4+. Xcode should instruct the linker to include libswiftCompatibilitySpan.dylib in the compiled bundle to provide this backdeployment, but that does not happen. SwiftPM does this additional linking by adding an rpath. When trying to load the bundle using the NSBundle.loadAndReturnError() API, I get the following error on macOS 15 (and no error on macOS 26): Error Domain=NSCocoaErrorDomain Code=3588 "dlopen(.../MyBundle.someBundle/Contents/MacOS/MyBundle, 0x0109): Library not loaded: @rpath/libswiftCompatibilitySpan.dylib Referenced from: <CE92806C-94B7-367E-895D-EF6DF66C7FC2> .../MyBundle.someBundle/Contents/MacOS/MyBundle Reason: tried: '/usr/lib/swift/libswiftCompatibilitySpan.dylib' (no such file, not in dyld cache), '/System/Volumes/Preboot/Cryptexes/OS/usr/lib/swift/libswiftCompatibilitySpan.dylib' (no such file), '/private/Frameworks/libswiftCompatibilitySpan.dylib' (no such file), '.../MyBundle.someBundle/Contents/MacOS/../Frameworks/libswiftCompatibilitySpan.dylib' (no such file), '/usr/lib/swift/libswiftCompatibilitySpan.dylib' (no such file, not in dyld cache), '/System/Volumes/Preboot/Cryptexes/OS/usr/lib/swift/libswiftCompatibilitySpan.dylib' (no such file), '/private/Frameworks/libswiftCompatibilitySpan.dylib' (no such file), '.../MyBundle.someBundle/Contents/MacOS/../Frameworks/libswiftCompatibilitySpan.dylib' (no such file)" UserInfo={NSLocalizedFailureReason=The bundle couldn’t be loaded., NSLocalizedRecoverySuggestion=Try reinstalling the bundle., NSFilePath=.../MyBundle.someBundle/Contents/MacOS/MyBundle, NSDebugDescription=dlopen(.../MyBundle.someBundle/Contents/MacOS/MyBundle, 0x0109): Library not loaded: @rpath/libswiftCompatibilitySpan.dylib Referenced from: <CE92806C-94B7-367E-895D-EF6DF66C7FC2> .../MyBundle.someBundle/Contents/MacOS/MyBundle Reason: tried: '/usr/lib/swift/libswiftCompatibilitySpan.dylib' (no such file, not in dyld cache), '/System/Volumes/Preboot/Cryptexes/OS/usr/lib/swift/libswiftCompatibilitySpan.dylib' (no such file), '/private/Frameworks/libswiftCompatibilitySpan.dylib' (no such file), '.../MyBundle.someBundle/Contents/MacOS/../Frameworks/libswiftCompatibilitySpan.dylib' (no such file), '/usr/lib/swift/libswiftCompatibilitySpan.dylib' (no such file, not in dyld cache), '/System/Volumes/Preboot/Cryptexes/OS/usr/lib/swift/libswiftCompatibilitySpan.dylib' (no such file), '/private/Frameworks/libswiftCompatibilitySpan.dylib' (no such file), '.../MyBundle.someBundle/Contents/MacOS/../Frameworks/libswiftCompatibilitySpan.dylib' (no such file), NSBundlePath=.../MyBundle.someBundle, NSLocalizedDescription=The bundle “MyBundle” couldn’t be loaded.} My setup: Xcode 26.2 macOS 26.2 (25C57) SDK (Built-in)
8
0
254
4d
Need a progress bar during init a document
I have no idea how to do it: on MacOS, in Document.init(configuration: ReadConfiguration) I decode file, and restore objects from data, which in some cases could take a long time. Document isn't fully inited, so I have no access to it. But would like to have a progress bar on screen (easier to wait for done, for now). I know size, progress value, but no idea how to make view from object during init. I know, this question may be very stupid. init(configuration: ReadConfiguration) throws { guard let data = configuration.file.regularFileContents else { throw CocoaError(.fileReadCorruptFile) } let decoder = JSONDecoder() let flat = try decoder.decode(FlatDoc.self, from: data) print ("reverting \(flat.objects.count) objects...") ///This takes time, a lot of time, need progress bar ///Total is `flat.objects.count`, current is `objects.count` /// `Show me a way to the (next) progress bar!` revertObjects(from: flat.objects) print ("...done") } update: I defined var flatObjects in Document, and I can convert in .onAppear. struct TestApp: App { @State var isLoading = false ... ContentView(document: file.$document) .onAppear { isLoading = true Task {file.document.revertObjects()} isLoading = false } if isLoading { ProgressView() } ... } But progress bar never shows, only rainbow ball
Topic: UI Frameworks SubTopic: SwiftUI Tags:
0
0
60
4d
Crash in UIKeyboardStateManager when repeatedly switching text input focus in WKWebView (hybrid app)
We’re building a hybrid iOS app using Angular (web) rendered inside a WKWebView, hosted by a native Swift app. Recently, we encountered a crash related to UIKeyboardStateManager in UIKit when switching between text inputs continuously within an Angular screen. Scenario The screen contains several text input fields. A “Next” button focuses the next input field programmatically. After about 61 continuous input field changes, the app crashes. It seems like this may be related to UIKit’s internal keyboard management while switching focus rapidly inside a WebView. crash stack: Crashed: com.apple.main-thread 0 WebKit 0xfbdad0 <redacted> + 236 1 UIKitCore 0x10b0548 -[UITextInteractionSelectableInputDelegate _moveToStartOfLine:withHistory:] + 96 2 UIKitCore 0xd0fb38 -[UIKBInputDelegateManager _moveToStartOfLine:withHistory:] + 188 3 UIKitCore 0xa16174 __158-[_UIKeyboardStateManager handleMoveCursorToStartOfLine:beforePublicKeyCommands:testOnly:savedHistory:force:canHandleSelectableInputDelegateCommand:keyEvent:]_block_invoke + 52 4 UIKitCore 0xa36ae4 -[_UIKeyboardStateManager performBlockWithTextInputChangesIgnoredForNonMacOS:] + 48 5 UIKitCore 0xa160f0 -[_UIKeyboardStateManager handleMoveCursorToStartOfLine:beforePublicKeyCommands:testOnly:savedHistory:force:canHandleSelectableInputDelegateCommand:keyEvent:] + 440 6 UIKitCore 0xa07010 -[_UIKeyboardStateManager handleKeyCommand:repeatOkay:options:] + 5760 7 UIKitCore 0xa2fb64 -[_UIKeyboardStateManager _handleKeyCommandCommon:options:] + 76 8 UIKitCore 0xa2fb08 -[_UIKeyboardStateManager _handleKeyCommand:] + 20 9 UIKitCore 0xa30684 -[_UIKeyboardStateManager handleKeyEvent:executionContext:] + 2464 10 UIKitCore 0xa2f95c __42-[_UIKeyboardStateManager handleKeyEvent:]_block_invoke + 40 11 UIKitCore 0x4b9460 -[UIKeyboardTaskEntry execute:] + 208 12 UIKitCore 0x4b92f4 -[UIKeyboardTaskQueue continueExecutionOnMainThread] + 356 13 UIKitCore 0x4b8be0 -[UIKeyboardTaskQueue addTask:breadcrumb:] + 120 14 UIKitCore 0x4a9ed0 -[_UIKeyboardStateManager _setupDelegate:delegateSame:hardwareKeyboardStateChanged:endingInputSessionIdentifier:force:delayEndInputSession:] + 3388 15 UIKitCore 0xfa290 -[_UIKeyboardStateManager setDelegate:force:delayEndInputSession:] + 628 16 UIKitCore 0xf617c -[UIKeyboardSceneDelegate _reloadInputViewsForKeyWindowSceneResponder:force:fromBecomeFirstResponder:] + 1140 17 UIKitCore 0xf5c88 -[UIKeyboardSceneDelegate _reloadInputViewsForResponder:force:fromBecomeFirstResponder:] + 88 18 UIKitCore 0x4fe4ac -[UIResponder(UIResponderInputViewAdditions) reloadInputViews] + 84 19 WebKit 0xfbe708 <redacted> + 100 20 WebKit 0xfbf594 <redacted> + 340 21 WebKit 0x8a33d8 <redacted> + 32 22 WebKit 0x8cee04 <redacted> + 144 23 WebKit 0x1c83f0 <redacted> + 22692 24 WebKit 0x73f40 <redacted> + 264 25 WebKit 0x162c7c <redacted> + 40 26 WebKit 0x1623b4 <redacted> + 1608 27 WebKit 0x73298 <redacted> + 268 28 WebKit 0x72e48 <redacted> + 660 29 JavaScriptCore 0xdb00 WTF::RunLoop::performWork() + 524 30 JavaScriptCore 0xd744 WTF::RunLoop::performWork(void*) + 36 31 CoreFoundation 0xf92c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 32 CoreFoundation 0xf744 __CFRunLoopDoSource0 + 172 33 CoreFoundation 0xf5a0 __CFRunLoopDoSources0 + 232 34 CoreFoundation 0xff20 __CFRunLoopRun + 840 35 CoreFoundation 0x11adc CFRunLoopRunSpecific + 572 36 GraphicsServices 0x1454 GSEventRunModal + 168 37 UIKitCore 0x135274 -[UIApplication _run] + 816 38 UIKitCore 0x100a28 UIApplicationMain + 336 39 APP1 0xa2ed0 main + 21 (AppDelegate.swift:21) 40 ??? 0x1aa889f08 (シンボルが不足しています) From reviewing the crash log, it appears that the crash occurs inside UIKeyboardStateManager while handling keyboard or cursor updates. Questions Has anyone seen this specific crash pattern involving UIKeyboardStateManager? Are there known UIKit or WebKit bugs related to UIKeyboardStateManager when continuously changing focus between text fields (especially in WKWebView)? Any insights or workarounds would be greatly appreciated. Thanks!
1
0
193
5d
Cannot overwrite Swift package default traits in Xcode
I am using swift-subprocess, and need to disable the SubprocessSpan trait because Xcode 26.2 does not ship with a bundled version libswiftCompatibilitySpan.dylib, causing everything to crash built with Xcode that happens to use Span. However, I cannot disable that trait by doing any of the following things: .package( url: "https://github.com/swiftlang/swift-subprocess.git", branch: "main", traits: [] ), .package( url: "https://github.com/swiftlang/swift-subprocess.git", branch: "main", traits: [.trait(name: "SubprocessFoundation")] ), Note that SubprocessSpan is default trait in subprocess: // Enable SubprocessFoundation by default var defaultTraits: Set<String> = ["SubprocessFoundation"] #if compiler(>=6.2) // Enable SubprocessSpan when Span is available [except it is not] defaultTraits.insert("SubprocessSpan") #endif The package still builds with the SubprocessSpan enabled. This is not an issue with the subprocess package. According to this, I should use swift build on the command line, yet this isn't -- as is upgrading to Tahoe -- an option because I need Xcode previews for SwiftUI. Help, what do I do now (other than downloading a toolchain) from swift.org)?
0
0
21
5d
Bug: Xcode 26.2 wants `ENABLE_DEBUG_DYLIB`: How do I enable that in `Package.swift`?
Xcode tells me Previewing in executable targets now requires a new build layout for unoptimized builds. Either set ENABLE_DEBUG_DYLIB to YES for this target, or break out your preview code into a separate framework with its own scheme. How do enable that in Package.swift. swiftSettings don't work (.define and unsafeFlags with -D ...). Creating a library product that the executable then depends on doesn't help either. I have two targets, one is an executable target. The #Preview macro is in the non-executable target.
1
1
33
5d
Installed Xcode - Canvas fails to boot
Downloaded Xcode 26.2 from App Store. Started new Project, which defaults to "hello world". The canvas "simulator" within fails to finish indexing (paused), or When the canvas is active, the first code change (i.e. just a return key at the end of a line) cause the Xcode program to come to a stop. Have ended Xcode and rebooted a number of times. A number of remedies are posted on the net. All a little different than the other. Is there a current remedy for Xcode 26.2 to this issue available? iMac on Sequoia 15.7.3 , 800 gb of available storage Xcode: 26.2 (24553) Instruments: 26.2 (64573.16) SDKs: DriverKit: 25.2: iOS: 26.2: (23C53) iOS Simulator: 26.2: (23C53) macOS: 26.2: (25C57) tvOS: 26.2: (23K50) tvOS Simulator: 26.2: (23K50) visionOS: 26.2: (23N301) visionOS Simulator: 26.2: (23N301) watchOS: 26.2: (23S303) watchOS Simulator: 26.2: (23S303)
1
0
98
5d
Crash in swift::_getWitnessTable when passing UITraitBridgedEnvironmentKey
When using UITraitBridgedEnvironmentKey to pass a trait value to the swift environment, it causes a crash when trying to access the value from the environment. The issue seems to be related to how swift uses the UITraitBridgedEnvironmentKey protocol since the crash occurs in swift::_getWitnessTable () from lazy protocol witness table accessor…. It can occur when calling any function that is generic using the UITraitBridgedEnvironmentKey type. I originally encountered the issue when trying to use a UITraitBridgedEnvironmentKey in SwiftUI, but have been able to reproduce the issue with any function with a similar signature. https://developer.apple.com/documentation/swiftui/environmentvalues/subscript(_:)-9zku Steps to Reproduce Requirements for the issue to occur Project with a minimum iOS version of iOS 16 Build the project with Xcode 26 Run on iOS 18 Add the following code to a project and call foo(key: MyCustomTraitKey.self) from anywhere. @available(iOS 17.0, *) func foo<K>(key: K.Type) where K: UITraitBridgedEnvironmentKey { // Crashes before this is called } @available(iOS 17.0, *) public enum MyCustomTraitKey: UITraitBridgedEnvironmentKey { public static let defaultValue: Bool = false public static func read(from traitCollection: UITraitCollection) -> Bool { false } public static func write(to mutableTraits: inout UIMutableTraits, value: Bool) {} } // The crash will occur when calling this. It can be added to a project anywhere // The sample project calls it from scene(_:willConnectTo:options:) foo(key: MyCustomTraitKey.self) For example, I added it to the SceneDelegate in a UIKit Project class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { if #available(iOS 17, *) { // The following line of code can be placed anywhere in a project, `SceneDelegate` is just a convenient place to put it to reproduce the issue. foo(key: MyCustomTraitKey.self) // ^ CRASH: Thread 1: EXC_BAD_ACCESS (code=1, address=0x10) } } } Actual Behaviour The app crashes with the stack trace showing the place calling foo but before foo is actually called. (ie, a breakpoint or print in foo is never hit) #0 0x000000019595fbc4 in swift::_getWitnessTable () #1 0x0000000104954128 in lazy protocol witness table accessor for type MyCustomTraitKey and conformance MyCustomTraitKey () #2 0x0000000104953bc4 in SceneDelegate.scene(_:willConnectTo:options:) at .../SceneDelegate.swift:20 The app does not crash when run on iOS 17, or 26 or when the minimum ios version is raised to iOS 17 or higher. It also doesn't crash on iOS 16 since it's not calling foo since UITraitBridgedEnvironmentKey was added in iOS 17. Expected behaviour The app should not crash. It should call foo on iOS 17, 18, and 26.
3
0
79
6d
Persisting User Settings with SwiftData
I was wondering what the recommended way is to persist user settings with SwiftData? It seems the SwiftData API is focused around querying for multiple objects, but what if you just want one UserSettings object that is persisted across devices say for example to store the user's age or sorting preferences. Do we just create one object and then query for it or is there a better way of doing this? Right now I am just creating: import SwiftData @Model final class UserSettings { var age: Int = 0 var sortAtoZ: Bool = true init(age: Int = 0, sortAtoZ: Bool = true) { self.age = age self.sortAtoZ = sortAtoZ } } In my view I am doing as follows: import SwiftUI import SwiftData struct SettingsView: View { @Environment(\.modelContext) var context @Query var settings: [UserSettings] var body: some View { ForEach(settings) { setting in let bSetting = Bindable(setting) Toggle("Sort A-Z", isOn: bSetting.sortAtoZ) TextField("Age", value: bSetting.age, format: .number) } .onAppear { if settings.isEmpty { context.insert(UserSettings(age: 0, sortAtoZ: true)) } } } } Unfortunately, there are two issues with this approach: I am having to fetch multiple items when I only ever want one. Sometimes when running on a new device it will create a second UserSettings while it is waiting for the original one to sync from CloudKit. AppStorage is not an option here as I am looking to persist for the user across devices and use CloudKit syncing.
3
0
230
6d
Push Notifications Error
Hi, I'm experiencing an issue with my app. I use Firebase as my server, and it is great. Still, there is one issue: when I send push notifications from my app to users, the users will get the notification if the app is open, but not when it is closed. I have tried many solutions to fix it, even asking AI, but the issue is still there. I would be happy to give you access to Firebase and the Xcode workspace, as I have no clue how to fix it.
1
0
41
6d
vDSP.DiscreteFourierTransform failed to initialize with 5 * 5 * 2^n count
I am implementing the FFT using vDSP.DiscreteFourierTransform. According to the official documentation, the count parameter has requirements as outlined below: /// The `count` parameter must be: /// * For split-complex real-to-complex: `2ⁿ` or `f * 2ⁿ`, where `f` is `3`, `5`, or `15` and `n >= 4`. /// * For split-complex complex-to-complex: `2ⁿ` or `f * 2ⁿ`, where `f` is `3`, `5`, or `15` and `n >= 3`. /// * For interleaved: `f * 2ⁿ`, where `f` is `2`, `3`, `5`, `3x3`, `3x5`, or `5x5`, and `n>=2`. Despite adhering to these specifications in theory, my attempt to initialize an interleaved DFT with count = 2 * 2 * 5 * 5 (equivalent to 5×5 × 2²) resulted in a failure. Below is the code snippet I used for the initialization: do { let dft = try vDSP.DiscreteFourierTransform( previous: nil, count: 2 * 2 * 5 * 5, direction: .forward, transformType: .complexReal, ofType: DSPComplex.self ) print(dft) } catch { print("DFT init failed:", error) } Could somebody more knowledgeable with these APIs have a look? Thanks!
1
0
475
6d
CXCallDirectoryProvider – Numbers added but blocking not working
Hi all, I'm working on a Call Directory Extension using CXCallDirectoryExtensionContext. I want to add a list of numbers to be blocked. Here's the function I use: override func beginRequest(with context: CXCallDirectoryExtensionContext) { context.delegate = self let blockedNumbers = loadNumberEntries(forKey: blockedKey) let identifiedNumbers = loadNumberEntries(forKey: identifiedKey) addAllBlocking(blockedNumbers, to: context) addAllIdentification(identifiedNumbers, to: context) context.completeRequest() } private func addAllBlocking(_ entries: [NumberEntry], to context: CXCallDirectoryExtensionContext) { let numbers: [Int64] = entries.compactMap { Int64($0.countryCode + $0.phone) }.sorted() for number in numbers { context.addBlockingEntry(withNextSequentialPhoneNumber: number) print("# Added blocking entry: \(number)") } } When I run this, I see in the console: # Added blocking entry: (*my number with country code*) So it seems the number is added correctly. However, in practice, the number is not blocked on the device. I’ve made sure that: The number is stored with the country code prefix. The extension is enabled in Settings → Phone → Call Blocking & Identification. The extension is reloaded after adding numbers. The array of numbers is sorted in ascending order before calling addBlockingEntry. Despite all this, the number still isn’t blocked. Does anyone know why the print shows the number added, but it doesn’t actually block the call? Am I missing something in the way CXCallDirectoryExtensionContext works? Thanks for any advice!
1
0
864
6d