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

BUG in implemented StoreKit External Link Account API in a Vue + Capacitor app
I would like to clarify that my app is a Reader APP and a hybrid application built with Vue.js and Capacitor. To comply with Apple’s guidelines, I am not using any third-party SDKs for account management or payments. Instead, I am attempting to use the official StoreKit External Link Account API as required. To achieve this, I created a custom native Capacitor plugin in Swift, which calls the StoreKit 2 classes (SKStoreExternalLinkAccountRequest and SKStoreExternalLinkAccountViewController) to present the required modal before redirecting users to manage their accounts externally. However, I am encountering a technical issue: When building the app in Xcode 16 (with iOS Deployment Target set to 16+), the Swift compiler cannot find the StoreKit 2 classes (SKStoreExternalLinkAccountRequest and SKStoreExternalLinkAccountViewController). I have attached a screenshot showing the error in Xcode. Could you please clarify if there are any additional requirements or steps needed to access these StoreKit 2 APIs in a hybrid (Capacitor/Vue) app? Is there any limitation for hybrid apps, or is there a specific configuration needed in Xcode or the project to make these APIs available? I am committed to fully complying with Apple’s guidelines and want to ensure the best and safest experience for my users. Any guidance or documentation you can provide would be greatly appreciated. my plugin: my app in xcode - build failed I would really appreciate it if someone could help me.
1
0
101
Jun ’25
How I can localize an array ?
Hello, I am trying to localize my app in other languages. Most of the text are automatically extracted by Xcode when creating a string catalog and running my app. However I realized few texts aren't extracted, hence I find a solution for most of them by adding For example I have some declared variable as var title: String = "Continue" Hence for them to be trigger I changed the String by LocalizedStringResource which gives var title: LocalizedStringResource = "Continue" But I still have an issue with some variables declared as an array with this for example @State private var genderOptions = ["Male", "Female", "Not Disclosed"] I tried many things however I don't success to make these arrays to be translated as the word here "Male", "Female" and "Not Disclosed". I have more array like that in my code and I am trying to find a solution for them to be extracted and be able to be localized Few things I tried that doesn't worked @State private var genderOptions : LocalizedStringResource = ["Male", "Female", "Not Disclosed"] @State private var genderOptions = [LocalizedStringResource("Male"), LocalizedStringResource("Female"), LocalizedStringResource("Not Disclosed")] Any idea more than welcome Thank guys
2
0
89
Jun ’25
Locale.Script seems to be returning a value even though the language has no script
We just dropped support for iOS 16 in our app and migrated to the new properties on Locale to extract the language code, region, and script. However, after doing this we are seeing an issue where the script property is returning a value when the language has no script. Here is the initializer that we are using to populate the values. The identifier is coming from the preferredLanguages property that is found on Locale. init?(identifier: String) { let locale = Locale(identifier: identifier) guard let languageCode = locale.language.languageCode?.identifier else { return nil } language = languageCode region = locale.region?.identifier script = locale.language.script?.identifier } Whenever I inspect locale.language I see all of the correct values. However, when I inspect locale.language.script directly it is always returning Latn as the value. If I inspect the deprecated locale.scriptCode property it will return nil as expected. Here is an example from the debugger for en-AU. I also see the same for other languages such as en-AE, pt-BR. Since the language components show the script as nil, then I would expect locale.language.script?.identifier to also return nil.
1
0
90
Jun ’25
Launching a Unity fully immersive game from SwiftUI
I am trying to launch a fully immersive game from Unity on a SwiftUI view. The game is using Metal Rendering with Compositor Services. I added the unity Xcode project into the workspace, added the necessary bridge code. When I click on the button to call ufw?.showUnityWindow(), it does not start and I get the following in the console: AR session failed to start after 5 seconds. Is the app configured to use an immersive space?
2
0
88
Jun ’25
Issue with Swift 6 migration issues
We are migrating to swift 6 from swift 5 using Xcode 16.2. we are getting below errors in almost each of our source code files : Call to main actor-isolated initializer 'init(storyboard:bundle:)' in a synchronous non isolated context Main actor-isolated property 'delegate' can not be mutated from a nonisolated context Call to main actor-isolated instance method 'register(cell:)' in a synchronous nonisolated context Call to main actor-isolated instance method 'setup()' in a synchronous nonisolated context Few questions related to these compile errors. Some of our functions arguments have default value set but swift 6 does not allow to set any default values. This requires a lot of code changes throughout the project. This would be lot of source code re-write. Using annotations like @uncheck sendable , @Sendable on the class (Main actor) name, lot of functions within those classes , having inside some code which coming from other classes which also showing main thread issue even we using @uncheck sendable. There are so many compile errors, we are still seeing other than what we have listed here. Fixing these compile errors throughout our project, would be like a re-write of our whole application, which would take lot of time. In order for us to migrate efficiently, we have few questions where we need your help with. Below are the questions. Are there any ways we can bypass these errors using any keywords or any other way possible? Can Swift 5 and Swift 6 co-exist? so, we can slowly migrate over a period of time.
1
0
141
Jun ’25
NEFilterManager saveToPreferences fails with "permission denied" on TestFlight build
I'm working on enabling a content filter in my iOS app using NEFilterManager and NEFilterProviderConfiguration. The setup works perfectly in debug builds when running via Xcode, but fails on TestFlight builds with the following error: **Failed to save filter settings: permission denied ** **Here is my current implementation: ** (void)startContentFilter { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; [userDefaults synchronize]; [[NEFilterManager sharedManager] loadFromPreferencesWithCompletionHandler:^(NSError * _Nullable error) { dispatch_async(dispatch_get_main_queue(), ^{ if (error) { NSLog(@"Failed to load filter: %@", error.localizedDescription); [self showAlertWithTitle:@"Error" message:[NSString stringWithFormat:@"Failed to load content filter: %@", error.localizedDescription]]; return; } NEFilterProviderConfiguration *filterConfig = [[NEFilterProviderConfiguration alloc] init]; filterConfig.filterSockets = YES; filterConfig.filterBrowsers = YES; NEFilterManager *manager = [NEFilterManager sharedManager]; manager.providerConfiguration = filterConfig; manager.enabled = YES; [manager saveToPreferencesWithCompletionHandler:^(NSError * _Nullable error) { dispatch_async(dispatch_get_main_queue(), ^{ if (error) { NSLog(@"Failed to save filter settings: %@", error.localizedDescription); [self showAlertWithTitle:@"Error" message:[NSString stringWithFormat:@"Failed to save filter settings: %@", error.localizedDescription]]; } else { NSLog(@"Content filter enabled successfully!"); [self showAlertWithTitle:@"Success" message:@"Content filter enabled successfully!"]; } }); }]; }); }]; } **What I've tried: ** Ensured the com.apple.developer.networking.networkextension entitlement is set in both the app and system extension. The Network extension target includes content-filter-provider. Tested only on physical devices. App works in development build, but not from TestFlight. **My questions: ** Why does saveToPreferencesWithCompletionHandler fail with “permission denied” on TestFlight? Are there special entitlements required for using NEFilterManager in production/TestFlight builds? Is MDM (Mobile Device Management) required to deploy apps using content filters? Has anyone successfully implemented NEFilterProviderConfiguration in production, and if so, how?
1
0
132
Jun ’25
Is Phase Detection Autofocus degrading video stabilization, and can I disable it?
I'm developing a video capture app using AVFoundation, designed specifically for use on a boat pylon to record slalom water skiing. This setup involves considerable vibration. As you may know, the OIS that Apple began adding to lenses since the iPhone 7 is actually very problematic in high vibration circumstances, ironically creating very shaky video, whereas lenses without OIS produce perfectly stable video. Because of this, up until iPhone 14, the solution for my app was simply to use the Selfie lens, which did not have OIS. Starting with iPhone 14 through iPhone 16 (non-Pro models), technical specs suggest the selfie lens still does not include OIS. However, I’m still seeing the same kind of shaky video behavior I see on OIS-equipped lenses. The one hardware change I see in this camera module is the addition of PDAF (Phase Detection Autofocus), so that is my best guess as to what is causing the unstable video. 1- Does that make any sense - that in high vibration settings, PDAF could create unstable video in the same way that OIS does? Or could it be something else that was changed between the iPhone 13 and 14 Selfie lens? Thinking that the issue was PDAF, I figured that if I enabled my app to set a Manual Focus level, that ought to circumvent PDAF (expecting that if a lens is manually focusing, it can’t also be autofocusing via PDAF). However, even with manual focus locked via AVCaptureDevice in my app, on the Selfie lens of an iPhone 16, the video still comes out very shaky, basically unusable. I also tested with the built-in Apple Camera app (using the press-and-hold to lock focus and exposure) and another 3rd party camera app to lock focus, all with the same results, so it's not that my app just isn't correctly doing manual focus. So I'm stuck with these questions: 2- Does the selfie camera on iPhones 14–16 use PDAF even when focus is set to locked/manual mode? 3- Is there any way in AVFoundation to disable or suppress PDAF during video recording (e.g., a flag, device format setting, or private API)? 4- Is PDAF behavior or suppression documented or controllable via AVCaptureDevice or any related class? 5- If no control of PDAF is available, are there any best practices for stabilizing or smoothing this effect programmatically? Note that I also have set my app to use the most aggressive form of stabilization available, so it defaults to .cinematicExtendedEnhanced, if that’s not available, then .cinematicExtended, etc. On the 16 Selfie lens, it is using .cinematicExtended. As an additional question: 6- Would those be the most appropriate stabilization settings for a high vibration environment, and if not, what would be best?
0
0
130
May ’25
App Randomly Crashes During Continuous Sound Playback Using AVAudioPlayer
Environment→ ・Device: iPad 10th generation ・OS:**iOS18.3.2 We're using AVAudioPlayer to play a sound when a button is tapped. In our use case, this button can be tapped very frequently — roughly every 0.1 to 0.2 seconds. Each tap triggers the following function: var audioPlayer: AVAudioPlayer? func soundPlay(resource: String, type: String){ guard let path = Bundle.main.path(forResource: resource, ofType: type) else { return } do { audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path)) audioPlayer!.delegate = self try audioSession.setCategory(.playback) } catch { return } self.audioPlayer!.play() } The issue is that under high-frequency tapping (especially around 0.1–0.15s intervals), the app occasionally crashes. The crash does not occur every time, but it happens randomly — sometimes within 30 seconds, within 1 minute, or even 3 minutes of continuous tapping. Interestingly, adding a delay of 0.2 seconds between button taps seems to prevent the crash entirely. Delays shorter than 0.2 seconds (e.g.,0.15s,0.18s) still result in occasional crashes. My questions are: **Is this expected behavior from AVAudioPlayer or AVAudioSession? Could this be a known issue or a limitation in AVFoundation? Is there any documentation or guidance on handling frequent sound playback safely?** Any insights or recommendations on how to handle rapid, repeated audio playback more reliably would be appreciated.
0
0
126
May ’25
Default zone is not accessible in shared DB - cloudKit
I am trying to save to cloud kit shared database. The shared database does not allow zones to be set up. How do I save to sharedCloudDatabase without a zone? private func addItem(recordType: String, name: String) { let record = CKRecord(recordType: recordType) record[Constances.field.name] = name as CKRecordValue record[Constances.field.done] = false as CKRecordValue record[Constances.field.priority] = 0 as CKRecordValue CKContainer.default().sharedCloudDatabase.save(record) { [weak self] returnRecord, error in if let error = error { print("Error saving record: \(record[Constances.field.name] as? String ?? "No Name"): \n \(error)") return } } } The following error message prints out: Error saving record: Milk: <CKError 0x15af87900: "Server Rejected Request" (15/2027); server message = "Default zone is not accessible in shared DB"; op = B085F7BA703D4A08; uuid = 87AEFB09-4386-4E43-81D7-971AAE8BA9E0; container ID = "iCloud.com.sfw-consulting.Family-List">
1
0
61
Jun ’25
Clearing an app’s memory, data etc.
My app works perfectly the first time it is used but when returning to the start after playing the game and playing another it does some random things. I figure it is because the app still retains the previous game in it’s memory allocation? My question is, what is the best way programmatically to have an app start fresh and not have to quit it and open it again?
6
0
131
May ’25
How to achieve a pure backdrop blur effect without predefined tint color in SwiftUI / UIKit?
Hi everyone, I’m currently trying to create a pure backdrop blur effect in my iOS app (SwiftUI / UIKit), similar to the backdrop-filter: blur(20px) effect in CSS. My goal is simple: • Apply a Gaussian blur (radius ~20px) to the background content • Overlay a semi-transparent black layer (opacity 0.3) • Avoid any predefined color tint from UIBlurEffect or .ultraThinMaterial, etc. However, every method I’ve tried so far (e.g., .ultraThinMaterial, UIBlurEffect(style:)) always introduces a built-in tint, which makes the result look gray or washed out. Even when layering a black color with opacity 0.3 over .ultraThinMaterial, it doesn’t give the clean, transparent-black + blur look I want. What I’m looking for: • A clean 20px blur effect (like CIGaussianBlur) • No color shift/tint added by default • A layer of black at 30% opacity on top of the blur • Ideally works live (not a static snapshot blur) Has anyone achieved something like this in UIKit or SwiftUI? Would really appreciate any insights, workarounds, or libraries that can help. Thanks in advance! Ben
3
0
114
Jun ’25
MPNowPlayingInfoCenter nowPlayingInfo throttled
Hello, I have been running into issues with setting nowPlayingInfo information, specifically updating information for CarPlay and the CPNowPlayingTemplate. When I start playback for an item, I see lock screen information update as expected, along with the CarPlay now playing information. However, the playing items are books with collections of tracks. When I select a new track(chapter) within the book, I set the MPMediaItemPropertyTitle to the new chapter name. This change is reflected correctly on the lock screen, but almost never appears correctly on the CarPlay CPNowPlayingTemplate. The previous chapter title remains set and never updates. I see "Application exceeded audio metadata throttle limit." in the debug console fairly frequently. From that a I figured that I need to minimize updates to the nowPlayingInfo dictionary. What I did: I store the metadata dictionary in a local dictionary and only set values in the main nowPlayingInfo dictionary when they are different from the current value. I kick off the nowPlayingInfo update via a task that initially sleeps for around 2 seconds (not a final value, just for my current testing). If a previous Task is active, it gets cancelled, so that only one update can happen within that time window. Neither of these things have been sufficient. I can switch between different titles entirely and the information updates (including cover art). But when I switch chapters within a title, the MPMediaItemPropertyTitle continues to get dropped. I know the value is getting set, because it updates on the lock screen correctly. In total, I have 12 keys I update for info, though with the above changes, usually 2-4 of them actually get updated with high frequency. I am running out of ideas to satisfy the throttling thresholds to accurately display metadata. I could use some advice. Thanks.
4
1
119
May ’25
Securely transmit UIImage to app running on desktop website
Hello everyone, I'm trying to figure out how to transmit a UIImage (png or tiff) securely to an application running in my desktop browser (Mac or PC). The desktop application and iOS app would potentially be running on the same local network (iOS hotspot or something) or have no internet connection at all. I'm trying to securely send over an image that the running desktop app could ingest. I was thinking something like a local server securely accepting image data from an iPhone. Any suggestions ideas or where to look for more info would be greatly appreciated! Thank you for your help.
1
0
77
May ’25
Enterprise Vendor Id changing when it shouldn't
Hi All, Really weird one here... I have two bundle ids with the same reverse dns name... com.company.app1 com.company.app2 app1 was installed on the device a year ago. app2 was also installed on the device a year ago but I released a new updated version and pushed it to the device via Microsoft InTunes. A year ago the vendor Id's matched as the bundle id's were on the same domain of com.company. Now for some reason the new build of app2 or any new app I build isn't being recognised as on the same domain as app1 even though the bundle id should make it so and so the Vendor Id's do not match and it is causing me major problems as I rely on the Vendor Id to exchange data between the apps on a certain device. In an enterprise environment, does anyone know of any other reason or things that could affect the Vendor Id? According to Apple docs, it seems that only the bundle name affects the vendor id but it isn't following those rules in this instance.
10
0
222
Jun ’25
CKSyncEngine on macOS: Automatic Fetch Extremely Slow Compared to iOS
Hi everyone, We’re currently using CKSyncEngine to sync all our locally persisted data across user devices (iOS and macOS) via iCloud. We’ve noticed something strange and reproducible: On iOS, when the CKSyncEngine is initialized with manual sync behavior, both manual calls to fetchChanges() and sendChanges() happen nearly instantly (usually within seconds). Automatic syncing is also very fast. On macOS, when the CKSyncEngine is initialized with manual sync behavior, fetchChanges() and sendChanges() are also fast and responsive. However, once CKSyncEngine is initialized with automatic syncing enabled on macOS: sendChanges() still appears to transmit changes immediately. But automatic fetching becomes significantly slower — often taking minutes to pick up changes from the cloud, even when new data is already available. Even manual calls to fetchChanges() behave as if they’re throttled or delayed, rather than performing an immediate fetch. Our questions: Is this delay in automatic (and post-automatic manual) fetch behavior on macOS expected, or possibly a bug? Are there specific macOS constraints that impact CKSyncEngine differently than on iOS? Once CKSyncEngine has been initialized in automatic mode, is fetchChanges() no longer treated as a truly manual trigger? Is there a recommended workaround to enable fast sync behavior on macOS — for example, by sticking to manual sync configuration and triggering sync using a CKSubscription-based mechanism when remote changes occur? Any guidance, clarification, or experiences from other developers (or Apple engineers) would be greatly appreciated — especially regarding maintaining parity between iOS and macOS sync performance. Thanks in advance!
0
0
72
May ’25
Best practices for accessing NavigationPath in child views
Hi all I'm reworking our app in SwiftUI. My ultimate goal is to access the NavigationPath from a child view which is used throughout different NavgationStacks. While searching for I came across different ways of achieving this. As I'm relatively new to SwiftUI it is hard to understand what the actual best practice seems to be. So for the use case. My app has a TabView and each Tab has its own NavigationStack which looks something like this struct TabNavigation: View { @State private var selectedProductType: StaticProductType = .all @StateObject private var appRouter = AppRouter() var body: some View { TabView(selection: $appRouter.selectedTab) { Overview(activeType: $selectedProductType) .tabItem { Label("Home", systemImage: "house") } .tag(Tab.home) AssortmentView(router: $appRouter.assortmentRouter, activeType: $selectedProductType) .tabItem { Label(String(localized: "assortment"), systemImage: "list.bullet") } .tag(Tab.assortment) } } The AssortmenView holds the NavigationStack and defines the routes. struct AssortmentView: View { @Binding var router: AssortmentRouter @Binding var activeType: StaticProductType var body: some View { NavigationStack(path: $router.navigationPath) { VStack { ProductTypeNavigation(activeType: $activeType) .padding(.top, 10) .padding(.horizontal, 10) Spacer() TabView(selection: $activeType) { ListNavigation(type: .all) .tag(StaticProductType.all) ListNavigation(type: .games) .tag(StaticProductType.games) ListNavigation(type: .digital) .tag(StaticProductType.digital) ListNavigation(type: .toys) .tag(StaticProductType.toys) ListNavigation(type: .movies) .tag(StaticProductType.movies) ListNavigation(type: .books) .tag(StaticProductType.books) } .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never)) } .addToolbar() .navigationDestination(for: AssortmentRouter.Route.self) { route in switch route { case .overview(let type): OverviewTypeView(type: type) case .productDetail(let productId): ProductDetailView(productId: productId) .environmentObject(router) case .productList: ProductList() } } } } } Through my app I often use a view to displaying products. This view is reused over different NavigationStacks. struct ProductDetailView: View { var productId: Int @StateObject private var viewModel: ProductDetailViewModel = ProductDetailViewModel() @State private var showErrorAlert = false @EnvironmentObject var router: AssortmentRouter var body: some View { VStack { if !viewModel.isRefreshing { let product = viewModel.product VStack { Text("Product: \(product.title)") NavigationLink(destination: ProductDetailView(productId: Product.preview.productId)) { Text("Test") } } .navigationTitle(product.title) } else { ProgressView() } }.task { await loadProduct() } .alert("Error", isPresented: $showErrorAlert, presenting: viewModel.localizedError) { _ in Button("Try again") { Task { await loadProduct() } } Button("Go Back", role: .cancel) { // access navigationPath } } message: { errorMessage in Text(errorMessage) } } @MainActor private func loadProduct() async { await viewModel.loadProduct(productId: productId) showErrorAlert = viewModel.localizedError != nil } } In this example I created an AppRouter which holds all information for the routes and some functions to accessing the NavigationPath. class AppRouter: ObservableObject { var assortmentRouter = AssortmentRouter() var selectedTab: Tab = .home func navigateTo(tab: Tab) { selectedTab = tab } } class AssortmentRouter: ObservableObject { var navigationPath = NavigationPath() enum Route: Hashable { case overview(type: StaticProductType) case productList case productDetail(productId: Int) } func navigateTo(route: Route) { navigationPath.append(route) } } This works fine as it is. The pro of this solution is that I don't have to pass the NavigationPath down each subview to use it as I can define it as EnvrionmentObject. The problem with this though, I like to reuse ProductDetailView also in my other NavigationStack which won't have a router binding of type AssortmentRouter as you can imagine. To come back to my initial question, what would be the best way to design this? Passing down a NavigationPath Binding and using different typing for navigationDestinaion values Define a callback which is passed as function parameter to the detail view Using dismiss, but I read that this is can lead to weird behaviour and bugs Any other option? Maybe changing the app architecture to handle this a better way Apolgize the long post, but I would be really glad to get some feedback on this, so I can do it the right way. Thank you very much
3
0
73
May ’25
SwiftUI Document-Based App Issues: Files Don't Appear in "Recents" When Created
I'm experiencing an issue with a SwiftUI document-based app where document files are not appearing in the "Recents" tab or anywhere in the Files app when created from the "Recents" tab. However, when creating documents from the "Browse" tab, they work as expected. When I print the URL of the created document, it shows a valid path, but when navigating to that path, the file doesn't appear. This seems to be a specific issue related to document creation while in the "Recents" tab. Steps to Reproduce Use Apple's demo app for document-based SwiftUI apps: https://developer.apple.com/documentation/swiftui/building-a-document-based-app-with-swiftui Run the app and navigate to the "Recents" tab in the Files app Create a new document Note that the document doesn't appear in "Recents" or anywhere in Files app Now repeat the process but create the document from the "Browse" tab - document appears correctly Environment: Xcode 16.3 iOS 18.4 Expected Behavior: Documents created while in the "Recents" tab should be saved and visible in the Files app just like when created from the "Browse" tab.
1
0
58
May ’25
No such module 'UnityFramework' ,Getting this message updating Xcode to latest version
After the update of the Xcode to latest version, I’m getting “No Such Module Unity Framework” as error. the complete information is below. I had to update the Xcode and the O.S as per the Apple Requirement from my older version of 14.x to latest 16.3. I had no issued running the Unity within my iOS App till the recent update. Previous Setup: Unity was successfully integrated into this iOS app and running fine before the update. As it was working till the Xcode version 14.3, i have not changed any code relevant to Unity. What I’ve Tried: a. Added UnityFramework.framework to “Link Binary with Libraries” and marked it as “Embed & Sign”. b. Verified Framework Search Paths include $(PROJECT_DIR)/UnityProject/build/Debug-iphoneos c. Cleaned build folder, deleted Derived Data d. Checked [CP] Embed Pods Frameworks step in Build Phases Stuck On: Xcode still throws "No such module 'UnityFramework'" — it’s as if the framework isn’t being built or seen from my main project. Request for Help: Has anyone encountered this issue post-Xcode 16.3 update from 14.x. I’d really appreciate any guidance, updated workflows, or even a checklist of steps for properly integrating Unity into an existing iOS app with the new Xcode build system.
0
0
61
May ’25