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

How to set accessibility-label to NSTextAttachment ?
I have the following method to insert @mentions to a text field: func insertMention(user: Token, at range: NSRange) -> Void { let tokenImage: UIImage = renderMentionToken(text: "@\(user.username)") let attachment: NSTextAttachment = NSTextAttachment() attachment.image = tokenImage attachment.bounds = CGRect(x: 0, y: -3, width: tokenImage.size.width, height: tokenImage.size.height) attachment.accessibilityLabel = user.username attachment.accessibilityHint = "Mention of \(user.username)" let attachmentString: NSMutableAttributedString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment)) attachmentString.addAttribute(.TokenID, value: user.id, range: NSRange(location: 0, length: 1)) attachmentString.addAttribute(.Tokenname, value: user.username, range: NSRange(location: 0, length: 1)) let mutableText: NSMutableAttributedString = NSMutableAttributedString(attributedString: textView.attributedText) mutableText.replaceCharacters(in: range, with: attachmentString) mutableText.append(NSAttributedString(string: " ")) textView.attributedText = mutableText textView.selectedRange = NSRange(location: range.location + 2, length: 0) mentionRange = nil tableView.isHidden = true } When I use XCode's accessibility inspector to inspect the text input, the inserted token is not read by the inspector - instead a whitespace is shown for the token. I want to set the accessibility-label to the string content of the NSTextAttachment. How?
1
1
815
Jul ’25
Dynamic Presentation Sheet Heights
In my application, I have NavigationStack presented as a sheet, and I intend to dynamically adjust its height while pushing views within it. I'm utilizing a global observable variable to manage the height and everything works fine except that the height changes abruptly without any animation. It abruptly transitions from one height to another. The issue can be reproduced using the following code: #Preview { @Previewable @State var height: CGFloat = 200 Text("Parent View") .sheet(isPresented: .constant(true)) { NavigationStack { Form { NavigationLink("Button") { RoundedRectangle(cornerRadius: 20) .fill(Color.blue) .frame(height: 200) .navigationTitle("Child") .onAppear { withAnimation { height = 300 } } } } .navigationTitle("Parent") .navigationBarTitleDisplayMode(.inline) .presentationDetents([.height(height)]) .onAppear { withAnimation { height = 150 } } } } }
3
0
88
Jul ’25
Our customer's events on calendar are disappeared
Our app provides a calendar that integrates with the default calendar app. Specifically, we use iOS EventKit to perform CRUD operations on calendar data. Recently, we have received reports from users that all of their events have disappeared. However, after reviewing our implementation and logs, we have not been able to identify the cause. Some users have also reported that all data in their default calendar app has disappeared as well. Does anyone have any idea what might be causing this? To delete an event within our app, users must press the delete button and then confirm the deletion in a dialog. Additionally, it is not possible to delete more than two events at once. We've seen many people in the community discussing a bug where calendar events disappear after updating to iOS 18. If you have any information about when or why this happens, we'd appreciate it if you could share your insights.
0
3
76
Jul ’25
How to call a Swift file directly from Angular using Capacitor?
Hi everyone, I’m working on a Capacitor app built with Angular, and I’m trying to call a Swift class directly from the root of the iOS project (next to AppDelegate.swift) without using a full Capacitor plugin structure. The Swift file is called RtspVlcPlugin.swift and looks like this: import Capacitor @objc(RtspVlcPlugin) public class RtspVlcPlugin: CAPPlugin { @objc func iniciar(_ call: CAPPluginCall) { call.resolve() } } In AppDelegate.swift I register it like this: if let bridge = self.window?.rootViewController as? CAPBridgeViewController { bridge.bridge?.registerPluginInstance(RtspVlcPlugin()) print("✅ RtspVlcPlugin registered.") } The registration message prints correctly in Xcode logs. But from Angular, when I try to call it like this: import { registerPlugin } from '@capacitor/core'; const RtspVlcPlugin: any = registerPlugin('RtspVlcPlugin'); RtspVlcPlugin.iniciar({ ... }); I get this error: {"code":"UNIMPLEMENTED"} So, even though the plugin is registered manually, it’s not exposing any methods to the Angular/Capacitor runtime. My question is: What is the correct way to access a manually created Swift class (in the root of the iOS project) from Angular via Capacitor? Thanks in advance!
1
0
116
Jul ’25
Capacitor iOS Plugin with MobileVLCKit – Swift Plugin Not Recognized from Angular
Hi everyone, I'm developing a Capacitor plugin to display an RTSP video stream using MobileVLCKit on iOS. The Android side works perfectly, but I can’t get the iOS plugin to work — it seems my Swift file is not being detected or recognized, even though I’ve followed the official steps. What works: I followed the Capacitor Plugin Development Guide. I implemented the Android version of the plugin in Java inside the android/ folder. Everything works perfectly from Angular: the plugin is recognized and calls execute correctly. The issue on iOS: I implemented the iOS part in Swift, using the official MobileVLCKit documentation. I initially placed my RtspVlcPlugin.swift file in the plugin’s iOS folder, as the docs suggest. Then I moved it directly into the main app’s ios/App/App/ folder next to AppDelegate.swift and tried manual registration. The problem: Even though I manually register the plugin with: if let bridge = self.window?.rootViewController as? CAPBridgeViewController { bridge.bridge?.registerPluginInstance(RtspVlcPlugin()) print("✅ Plugin RtspVlcPlugin registered manually.") } It prints the registration message just fine. BUT from Angular, the plugin is not recognized: Capacitor.Plugins.RtspVlcPlugin has no methods, and I get this error: "code":"UNIMPLEMENTED" I also tried declaring @objc(RtspVlcPlugin) and extending CAPPlugin. I’ve verified RtspVlcPlugin.swift is added to the target and compiled. The Swift file doesn’t seem to register or expose any methods to Angular. I even tried adding the code without using a plugin at all — just creating a Swift class and using it via the AppDelegate, but it still doesn't expose any callable methods. My Swift code (RtspVlcPlugin.swift): import Capacitor import MobileVLCKit @objc(RtspVlcPlugin) public class RtspVlcPlugin: CAPPlugin, VLCMediaPlayerDelegate { var mediaPlayer: VLCMediaPlayer? var containerView: UIView? var spinner: UIActivityIndicatorView? @objc func iniciar(_ call: CAPPluginCall) { guard let urlStr = call.getString("url"), let x = call.getDouble("x"), let y = call.getDouble("y"), let w = call.getDouble("width"), let h = call.getDouble("height"), let url = URL(string: urlStr) else { call.reject("Missing parameters") return } DispatchQueue.main.async { self.containerView?.removeFromSuperview() let cont = UIView(frame: CGRect(x: x, y: y, width: w, height: h)) cont.backgroundColor = .black cont.layer.cornerRadius = 16 cont.clipsToBounds = true let sp = UIActivityIndicatorView(style: .large) sp.center = CGPoint(x: w/2, y: h/2) sp.color = .white sp.startAnimating() cont.addSubview(sp) self.spinner = sp self.containerView = cont self.bridge?.viewController?.view.addSubview(cont) let player = VLCMediaPlayer() player.delegate = self player.drawable = cont player.media = VLCMedia(url: url) self.mediaPlayer = player player.play() call.resolve() } } @objc func cerrar(_ call: CAPPluginCall) { DispatchQueue.main.async { self.mediaPlayer?.stop() self.mediaPlayer = nil self.spinner?.stopAnimating() self.spinner?.removeFromSuperview() self.spinner = nil self.containerView?.removeFromSuperview() self.containerView = nil call.resolve() } } public func mediaPlayerStateChanged(_ aNotification: Notification!) { guard let player = mediaPlayer, player.state == .playing, let sp = spinner else { return } DispatchQueue.main.async { sp.stopAnimating() sp.removeFromSuperview() self.spinner = nil } } } In the Angular project, I’m using the plugin by manually registering it with registerPlugin from @capacitor/core. Specifically, in the service where I need it, I do the following: import { registerPlugin } from '@capacitor/core'; const RtspVlcPlugin: any = registerPlugin('RtspVlcPlugin'); After this, I try to call the methods defined in the iOS plugin, like RtspVlcPlugin.iniciar({ ... }), but I get an UNIMPLEMENTED error, which suggests that the plugin is not exposing its methods properly to the Angular/Capacitor environment. That makes me believe the problem lies in how the Swift file is integrated or registered, rather than how it is used from Angular. I’d appreciate any guidance on how to properly expose a Swift-based Capacitor plugin’s methods so that they are accessible from Angular. Is there any additional registration step or metadata I might be missing on the iOS side?
1
0
142
Jul ’25
Clarification on safeAreaBar
I've been testing the safeAreaBar modifier to develop a custom tab bar. From my understanding, this should enable the .scrollEdgeEffectStyle to work with this bar, but I don't see any effect. Could you please clarify the difference between safeAreaBar and safeAreaInset?
Topic: UI Frameworks SubTopic: SwiftUI Tags:
4
3
155
4w
Execute Swift scripts dynamically in iOS
I have a transformation function that takes in data, executes some instructions, and returns an output. This function is dynamic and not shipped with the binary. Currently, I’m executing it using JavaScriptCore.JSContext, which works well, but the function itself is written in JavaScript. Is there a way to achieve something similar using Swift – such as executing a dynamic Swift script, either directly or through other means? I know this is possible on macOS, but I’m not sure about iOS. I’ve also heard that extensions might open up some possibilities here. Any insights or alternative approaches would be appreciated.
4
0
311
Jul ’25
Which in-app events are allowed without ATT consent?
Hi everyone, I'm developing an iOS app using the AppsFlyer SDK. I understand that starting with iOS 14.5, if a user denies the App Tracking Transparency (ATT) permission, we are not allowed to access the IDFA or perform cross-app tracking. However, I’d like to clarify which in-app events are still legally and technically safe to send when the user denies ATT permission. Specifically, I want to know: Is it acceptable to send events like onboarding_completed, paywall_viewed, subscription_started, subscribe, subscribe_price, or app_opened if they are not linked to IDFA or any form of user tracking? Would sending such internal behavioral events (used purely for SKAdNetwork performance tracking or in-app analytics) violate Apple’s privacy policy if no device identifiers are attached? Additionally, if these events are sent in fully anonymous form (i.e., not associated with IDFA, user ID, email, or any identifiable metadata), does Apple still consider this a privacy concern? In other words, can onboarding_completed, paywall_viewed, subsribe, subscribe_price, etc., be sent in anonymous format without violating ATT policies? Are there any official Apple guidelines or best practices that outline what types of events are considered compliant in the absence of ATT consent? My goal is to remain 100% compliant with Apple’s policies while still analyzing meaningful user behavior to improve the in-app experience. Any clarification or pointers to documentation would be greatly appreciated. Thanks in advance!
0
0
83
Jun ’25
No more simulators showing in Xcode
I sometimes use Xcode 14.2. Recently, I have an issue with simulators: on some SwiftUI project, the simulator list is empty. I created a new project. I see the complete list of simulators, but when running for a simulator, it fails with following diag; Same error with UIKit project. Details Unable to boot the Simulator. Domain: NSPOSIXErrorDomain Code: 60 Failure Reason: launchd failed to respond. User Info: { DVTErrorCreationDateKey = "2025-06-29 06:16:35 +0000"; IDERunOperationFailingWorker = "_IDEInstalliPhoneSimulatorWorker"; Session = "com.apple.CoreSimulator.SimDevice.134EC197-BA6B-45DF-B5B2-61A1D4F14863"; } -- Failed to start launchd_sim: could not bind to session, launchd_sim may have crashed or quit responding Domain: com.apple.SimLaunchHostService.RequestError Code: 4 -- Analytics Event: com.apple.dt.IDERunOperationWorkerFinished : { "device_model" = "iPhone15,2"; "device_osBuild" = "16.2 (20C52)"; "device_platform" = "com.apple.platform.iphonesimulator"; "launchSession_schemeCommand" = Run; "launchSession_state" = 1; "launchSession_targetArch" = "x86_64"; "operation_duration_ms" = 8341; "operation_errorCode" = 60; "operation_errorDomain" = NSPOSIXErrorDomain; "operation_errorWorker" = "_IDEInstalliPhoneSimulatorWorker"; "operation_name" = IDERunOperationWorkerGroup; "param_consoleMode" = 0; "param_debugger_attachToExtensions" = 0; "param_debugger_attachToXPC" = 1; "param_debugger_type" = 3; "param_destination_isProxy" = 0; "param_destination_platform" = "com.apple.platform.iphonesimulator"; "param_diag_MainThreadChecker_stopOnIssue" = 0; "param_diag_MallocStackLogging_enableDuringAttach" = 0; "param_diag_MallocStackLogging_enableForXPC" = 1; "param_diag_allowLocationSimulation" = 1; "param_diag_checker_tpc_enable" = 1; "param_diag_gpu_frameCapture_enable" = 0; "param_diag_gpu_shaderValidation_enable" = 0; "param_diag_gpu_validation_enable" = 0; "param_diag_memoryGraphOnResourceException" = 0; "param_diag_queueDebugging_enable" = 1; "param_diag_runtimeProfile_generate" = 0; "param_diag_sanitizer_asan_enable" = 0; "param_diag_sanitizer_tsan_enable" = 0; "param_diag_sanitizer_tsan_stopOnIssue" = 0; "param_diag_sanitizer_ubsan_stopOnIssue" = 0; "param_diag_showNonLocalizedStrings" = 0; "param_diag_viewDebugging_enabled" = 1; "param_diag_viewDebugging_insertDylibOnLaunch" = 1; "param_install_style" = 0; "param_launcher_UID" = 2; "param_launcher_allowDeviceSensorReplayData" = 0; "param_launcher_kind" = 0; "param_launcher_style" = 0; "param_launcher_substyle" = 0; "param_runnable_appExtensionHostRunMode" = 0; "param_runnable_productType" = "com.apple.product-type.application"; "param_runnable_type" = 2; "param_testing_launchedForTesting" = 0; "param_testing_suppressSimulatorApp" = 0; "param_testing_usingCLI" = 0; "sdk_canonicalName" = "iphonesimulator16.2"; "sdk_osVersion" = "16.2"; "sdk_variant" = iphonesimulator; } -- System Information macOS Version 12.7.1 (Build 21G920) Xcode 14.2 (21534) (Build 14C18) Timestamp: 2025-06-29T08:16:35+02:00 I filed a bug report: FB18475006
1
0
148
Jun ’25
HotKey support for sandboxed apps
App design: macos, Xcode 16.4, Sequioa 15.5, it is sandboxed Uses: Pods->HotKey for a global hotkey which xcode says "binary compatibility can't be guaranteed" This app is on the Apple Store and supposedly apps on the Apple Store can't use global hotkeys. Someone internally, installed it from the store and the global hotkey works just fine. I'm concerned for two potential problems; I need to find a hotkey library or code that is known to work with a sandbox'd Apple Store app. Why is it working now when everything I have read says it shouldn't.
0
0
104
Jun ’25
Unknown CHHapticError.Code (1852797029 == 'nope') in iOS 18+ on iPhone 11 Pro
Hello, I'm getting this error when launching a SpriteKit Swift game in iOS 18+ on an iPhone 11 Pro, whose shell is partly damaged in the back: CHHapticEngine.mm:1206 -[CHHapticEngine doStartWithCompletionHandler:]_block_invoke: ERROR: Player start failed: The operation couldn’t be completed. (com.apple.CoreHaptics error 1852797029.) Haptics do not work on this device, due to the damaged shell, so some error — which obviously occurs when calling start(completionHandler:) — is definitely expected; what is not expected is the main thread sometimes blocking for up to 5 seconds — although the method is not called from the main thread... the error itself is always displayed from some other secondary (system) thread. During this time, the main thread does not access the haptics engine at all; on average, it blocks once every four or five launches. In each launch (blocking or not), the 'nope' error is displayed ~5 seconds after trying to start the engine. After going nuts with all kinds of breakpoints and instrumentation, I'm at a loss as to why the main thread would sometimes block... Ideas, anyone? Thank you, D.
2
0
104
Jul ’25
How to fix iOS 26 Beta / iOS 18 SDK compile conflicts?
A method in my app now requires the override keyword when compiling with Xcode 26 beta / iOS 26 SDK, but if I add it, the current official Xcode 16.4 (iOS 18 SDK) throws a compile error. It's about 'toggleSidebar(_:)' in UIViewController. The problem is: Apple expects our apps to be ready for iOS 26 launch this fall, so I need to be actively developing and testing in the Xcode 26 beta now. At the same time, I still need to submit updates to the App Store using the current official Xcode 16.4 until iOS 26 officially launches. I'm using a single .xcodeproj file and can't keep manually adding/removing -DIOS_SDK_26_OR_LATER in Build Settings multiple times a day. How to fix it and why isn't there a straightforward #if sdk(>=26.0) type of check for compile-time in Swift? It's really frustrating to manage this override conflict.
1
0
111
Jul ’25
Why does a Swift test think my simple struct is main actor-isolated?
My experience with Swift 6 strict concurrency so far doesn't match my understanding of implicit MainActor isolation semantics. This is a cross-post from StackOverflow. I will link answers between both forums. TL;DR Build succeeds when testing a struct declared in the test module, but fails when the struct is moved to the main module: Main actor-isolated property … cannot be accessed from outside the actor. Steps to reproduce Open up Xcode 26 beta 2 on macOS 26 (probably also ok on current stables). Create a new Swift app with Swift testing, no storage. Call it WhatTheSwift. Set the Swift Language Version on all three targets to Swift 6. Update the default test file to be this: import Testing @testable import WhatTheSwift struct WhatTheSwiftTests { @Test func example() async throws { let thing = Thing(foo: "bar") #expect(thing.foo == "bar") } } struct Thing { let foo: String } That should build fine, and the tests should pass. Now, move the Thing declaration into its own Thing.swift file in the WhatTheSwift module, and try running the test again. You should see this: Observations Marking the test @MainActor allows the test to pass, suggesting the compiler actually wants to isolate Thing.foo to the main actor. My question Why? And why only when Thing is in a different module?
2
0
183
Jun ’25
External Keyboard + Voiceover focus not working with .searchable + List
While editing the search text using the external keyboard (with VoiceOver on), if I try to navigate the to List using the keyboard, the focus jumps back to the search field immediately, preventing selection of list items. It's important to note that the voiceover navigation alone without a keyboard works as expected. It’s as if the List never gains focus—every attempt to move focus lands back on the search field. The code: struct ContentView: View { @State var searchText = "" let items = ["Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grape"] var filteredItems: [String] { if searchText.isEmpty { return items } else { return items.filter { $0.localizedCaseInsensitiveContains(searchText) } } } var body: some View { if #available(iOS 16.0, *) { NavigationStack { List(filteredItems, id: \.self) { item in Text(item) } .navigationTitle("Fruits") .searchable(text: $searchText) } } else { NavigationView { List(filteredItems, id: \.self) { item in Text(item) } .navigationTitle("Fruits") .searchable(text: $searchText) } } } }
1
0
64
Jun ’25
Can `UIApplication.shared.setAlternateIconName` use .icon file?
I’m updating my app’s alternate icons using UIApplication.shared.setAlternateIconName, and I noticed that in iOS 26, Xcode now supports the new .icon file format for App Icons. Is it possible to reference .icon files directly for alternate icons? Or does setAlternateIconName still only support traditional .png assets inside the AppIcon set? I couldn’t find any documentation confirming this either way, and I want to ensure compatibility with the new format while supporting alternate icons. Any clarification or Apple documentation link would be greatly appreciated!
0
0
173
Jun ’25
XCode 26 beta 2 build error with AVAsset loading
I have this build error with Xcode 26 beta 2: var asset:AVURLAsset? func loadAsset() { let assetURL = URL.documentsDirectory .appendingPathComponent("sample.mov") asset = AVURLAsset(url: assetURL, options: [AVURLAssetPreferPreciseDurationAndTimingKey: true]) /*Error: Type of expression is ambiguous without a type annotation */ if let result = try? await asset?.load(.tracks, .isPlayable, .isComposable) { } } Is there an issue with try? in the new Swift compiler? Error: Type of expression is ambiguous without a type annotation
0
0
87
Jun ’25
Compiling Swift Package with Dependency on Build Tool Plugin Fails in Xcode 26
Hi, in our Xcode project we have a Tooling package, which defines build tool plugins for generating compile time safe constants for our localization strings as well as assets using swiftgen. This is working very well in Xcode 16, but fails in Xcode 26 beta 1 and beta 2 as well. The failure is specifically: unsupported configuration: the aggregate target 'Localization' has package dependencies, but targets that build for different platforms depend on it. I've reduced this to a minimal sample project, which you can find here.. To reproduce: Open the Repro workspace, that is attached in Xcode. Try to build TestyPackage. You'll see the error. I've filed this bug during WWDC week, but no feedback yet and no solution in Xcode 26 beta 2. Here's the feedback number, in case you have this too and want to file a duplicate: FB17934050. Does anyone else have this issue and perhaps a solution?
2
3
138
Jul ’25
Apple Watch no longer connects reliably in Xcode
Hi all, I'm developing a standalone SwiftUI watchOS app (no iOS host or extension), targeting watchOS 11.5, and running into persistent connection issues with Xcode. Xcode rarely detects my Apple Watch (Series 7, watchOS 11.5) Sometimes it appears nested under the iPhone; most of the time, it doesn’t Errors include: "OS version is lower than the deployment target" (both are 11.5) "Unable to install... device not supported" "Connection error 4000", "Tunnel timeout error 1001" "Ensure Wi-Fi is enabled on both machines" (Wi-Fi is on and on the same network) Once in a while, the app does install, but mostly I’m blocked. What I’ve Tried Verified pairing and trust Cleaned builds, nuked Derived Data and caches Reset iPhone privacy settings Removed and re-added my Apple ID Used xcrun xctrace list devices (watch inconsistently appears) Despite this, the app only installs about 5% of the time. Testing (or even running) on real hardware is nearly impossible, and has become incredibly frustrating for me. Any help or insights would be much appreciated.
1
0
52
Jun ’25