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

Swift/C++ interoperability issue in std::string
In scope of one of our project we've faced an issue with constant crashes when integrating C++ library in Swift code using Swift/C++ interoperability. Investigating the root causes of the issue we've discovered that with new version of Swift bug was introduced. Long story short: for strings bigger than 27 symbols memory is feed incorrectly that causes the crashes. By creating this post I wanted to draw community's attention to the problem and promote it to be solved quicker as for now it is not addressed.
1
0
486
2w
Exposing Objective-C API to Swift inside a Framework (Private Framework API)
My framework has private Objective-C API that is only used within the framework. It should not be exposed in the public interface (so it shouldn't be imported in the umbrella header). To expose this API to Swift that's within the framework only the documentation seems to indicate that this needs to be imported in the umbrella header? Import Code Within a Framework Target To use the Objective-C declarations in files in the same framework target as your Swift code, configure an umbrella header as follows: 1.Under Build Settings, in Packaging, make sure the Defines Module setting for the framework target is set to Yes. 2.In the umbrella header, import every Objective-C header you want to expose to Swift. Swift sees every header you expose publicly in your umbrella header. The contents of the Objective-C files in that framework are automatically available from any Swift file within that framework target, with no import statements. Use classes and other declarations from your Objective-C code with the same Swift syntax you use for system classes. I would imagine that there must be a way to do this?
0
0
228
2w
Avoiding Plugin Execution in a Linked Swift Package During Top-Level Package Builds
I am working on an iOS project using Xcode 16.0 that leverages multiple Swift packages. Among these, I have a Shared Package that contains reusable code and is linked to several top-level feature packages (e.g., VideoPlayer, VideoEditor, etc.). The Shared Package includes a Swift Package Manager plugin for linting code standards, which is designed to execute during its own build process. However, when building a top-level package (e.g., VideoPlayer), the Shared Package is also built as part of the dependency graph. During this process, the linting plugin in the Shared Package is executed unnecessarily, even though the intent is to only build the Shared Package's code. This behavior results in a significant increase in build times for the top-level packages, as the linting plugin is executed every time the Shared Package is built indirectly. Key Details: Xcode Version: 16.0 Swift Package Manager: Used for dependency management. Issue: The linting plugin in the Shared Package executes during the build of top-level packages, increasing build times. Expected Behaviour: The plugin should only execute when the Shared Package is built directly, not when it is built as a dependency of a top-level package. I would like to know if there is a way to configure the Shared Package or the Swift Package Manager to prevent the plugin from executing when the Shared Package is built as a dependency of a top-level package, while still allowing the plugin to run when the Shared Package is built directly. Any guidance, configuration tips, or best practices to address this issue would be greatly appreciated.
0
0
38
2w
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
801
2w
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
76
1w
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
69
2w
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
109
2w
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
121
2w
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:
2
2
81
2w
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
257
3d
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
56
3w
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
127
3w
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
91
3w
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
76
2w
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
85
6h
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
174
3w
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
48
3w
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
149
3w