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

Posts under Swift tag

200 Posts

Post

Replies

Boosts

Views

Activity

Example of DNS Proxy Provider Network Extension
I am trying to setup a system-wide DNS-over-TLS for iOS that can be turned off and on from within the app, and I'm struggling with the implementation details. I've searched online, searched forums here, used ChatGPT, and I'm getting conflicting information or code that is simply wrong. I can't find example code that is valid and gets me moving forward. I think I need to use NEDNSProxyProvider via the NetworkExtension. Does that sound correct? I have NetworkExtension -> DNS Proxy Capability set in both the main app and the DNSProxy extension. Also, I want to make sure this is even possible without an MDM. I see conflicting information, some saying this is opened up, but things like https://developer.apple.com/documentation/Technotes/tn3134-network-extension-provider-deployment saying a device needs to be managed. How do private DNS apps do this without MDM? From some responses in the forums it sounds like we need to parse the DNS requests that come in to the handleNewFlow function. Is there good sample code for this parsing? I saw some helpful information from Eskimo (for instance https://developer.apple.com/forums/thread/723831 ) and Matt Eaton ( https://developer.apple.com/forums/thread/665480 )but I'm still confused. So, if I have a DoT URL, is there good sample code somewhere for what startProxy, stopProxy, and handleNewFlow might look like? And valid code to call it from the main app?
10
0
224
2w
StoreKit Products Load After Rebuild But Not on Fresh Install (iOS/SwiftUI)
Problem: I'm implementing StoreKit 2 in my SwiftUI app. Products load successfully when I rebuild in Xcode, but on a fresh install, Product.products(for:) returns an empty array. The paywall shows "Unable to load pricing." Setup: Using StoreKit Configuration File ( .storekit ) for testing Product IDs match exactly between config and code: com..premium.lifetime (non-consumable) com..premium.monthly (auto-renewable subscription) com.****.premium.yearly (auto-renewable subscription) StoreKitManager is a @MainActor singleton with @Published properties What I've Tried: Initial delay before loading - Added 1-second delay in init before calling loadProducts() Product ID verification - Confirmed IDs match exactly between StoreKitConfig.storekit and code Retry logic with exponential backoff - Implemented 3 retry attempts with 0.5s/1s/1.5s delays Multiple calls to updatePurchasedProducts() - Called twice after initial load Verified StoreKit configuration - File is properly added to project, has valid product definitions Code Structure: swift @MainActor final class StoreKitManager: ObservableObject { static let shared = StoreKitManager() @Published private(set) var products: [Product] = [] private init() { updateListenerTask = listenForTransactions() Task { try? await Task.sleep(nanoseconds: 1_000_000_000) await loadProducts() // Returns empty on fresh install await updatePurchasedProducts() } } } Observations: ✅ Works perfectly after Xcode rebuild ❌ Fails on fresh app install (simulator & device) ❌ Product.products(for:) returns empty array (no error thrown) ✅ StoreKit configuration file is valid and properly configured Question: Why does StoreKit need a rebuild to recognize products? Is there a proper initialization sequence I'm missing for fresh installs? Environment: Xcode [Version 26.0 beta 7] iOS [IOS +17.0] Testing with StoreKit Configuration File
0
0
66
3w
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
786
3w
Why does AppStore.requestReview(in:) require NSViewController Parameter?
Looking to update one of my apps that uses SKStoreReviewController +requestReview (deprecated) to AppStore.requestReview(in:) umm...I have a few of questions... Why is an NSViewController parameter required? It's really not so uncommon for an AppKit app to just use NSWindowController with a window that does not use NSViewController... It should be possible to present the review request in a standalone alert (attached to a window is preferred IMO but it still should be possible to ask in separate window). 3)...why Swift..(err nevermind) Ideally: AppStore requestReview should take a NSWindow parameter but that parameter should be optional. If nil the request should be presented in a standalone window (like an alert). If non nil..present as a sheet on the window. Why a view controller? Maybe I'm missing something.
2
0
88
3w
SwiftUI Controls Documentation
Hi, I am looking for comprehensive "controls" documentation for SwiftUI. When searching on the Apple site, I have not seen any documentation that shows a picture of a control and an explantation of what it does, for all the available controls. I have also searched the web for such documentation, and have not found any. When I was learning Rust, I came across a beautiful document about GTK3 (PDF) that had a complete list of controls, including pictures. If something looked interesting I could do a search for more details. Thanks, Jim
1
0
135
3w
How can I render a ScrollView so that its ScrollPosition is at the correct ID during layout?
Below you will find an example view of my problem. It has one button that, when pressed, will toggle between two scroll views using withAnimation, setting the scroll position onto the 2nd and 3rd items for either scroll view in onAppear. The intent is to have the background of items within each list transition smoothly from their position in one list, to their position in the other. However, this does not appear to be easily possible when setting the list position using an ID/ScrollPosition: Initializing a ScrollPosition with the correct ID and rendering the ScrollView with that appears to have no effect - the ScrollView will be drawn at the top of the scroll contents The only way I've found to render the ScrollView at an ID position is to scroll to that position in onAppear. However, it appears that when doing so, the matchedGeometryEffect interpolates the position of the elements as if the contentOffset.y of the ScrollView is briefly 0, resulting in a strange effect The desired animation can be seen if the two lists are toggled rapidly, allowing for the matchedGeometryEffect to smooth out the brief y 0 and interpolate between the correct positions It seems I either need to a) ensure the list is laid out at the correct y location beforehand (very difficult with dynamic list items, but seems to solve this problem if setting the y position explicitly) b) ensure that the list is laid out at the correct ID beforehand (have not been able to figure out how) c) ensure the matched geometry effect animation ignores the brief "0" y offset of the ScrollView before setting the ID position in onAppear (have not been able to figure out how) Note that I have to use VStack here for the matched geometry effect to work consistently. Any ideas on solving this? Code: import SwiftUI struct Item: Identifiable { let id = UUID().uuidString var height: CGFloat var label: String } enum TestScrollListStyle { case primary case alternate } struct TestScrollList: View { let items: [Item] let style: TestScrollListStyle let namespace: Namespace.ID @Binding var scrollPosition: ScrollPosition var initialIndex: Int = 2 var body: some View { ScrollView { VStack(spacing: style == .primary ? 8 : 16) { ForEach(items, id: \.id) { item in switch style { case .primary: Text(item.label) .frame(maxWidth: .infinity) .frame(height: item.height) .padding(.horizontal) .background( Rectangle() .fill(.blue.opacity(0.15)) .matchedGeometryEffect(id: item.id, in: namespace) ) case .alternate: HStack { Circle() .fill(.green.opacity(0.25)) .frame(width: 24, height: 24) Text(item.label) .frame(maxWidth: .infinity, alignment: .leading) } .frame(height: item.height) .padding(.horizontal) .background( Rectangle() .fill(.green.opacity(0.08)) .matchedGeometryEffect(id: item.id, in: namespace) ) } } } .scrollTargetLayout() .padding(.vertical) } .scrollPosition($scrollPosition, anchor: .top) .onAppear { var tx = Transaction() tx.disablesAnimations = true withTransaction(tx) { if items.indices.contains(initialIndex) { scrollPosition.scrollTo(id: items[initialIndex].id) } } } } } struct ContentView: View { @Namespace private var matchedNamespace @State private var items: [Item] = (0..<10).map { i in Item(height: .random(in: 80...220), label: "Row \(i)") } @State private var showAlternateView: Bool = false // Scroll positions for each scroll view @State private var primaryScrollPosition = ScrollPosition(idType: String.self) @State private var alternateScrollPosition = ScrollPosition(idType: String.self) var body: some View { NavigationStack { ZStack { if !showAlternateView { TestScrollList( items: items, style: .primary, namespace: matchedNamespace, scrollPosition: $primaryScrollPosition, initialIndex: 2 ) } if showAlternateView { TestScrollList( items: items, style: .alternate, namespace: matchedNamespace, scrollPosition: $alternateScrollPosition, initialIndex: 3 ) } } .navigationTitle("Two ScrollViews + Matched Geometry") .toolbar { ToolbarItem(placement: .topBarTrailing) { Button(showAlternateView ? "Primary" : "Alternate") { withAnimation() { showAlternateView.toggle() } } } } } } } #Preview { ContentView() }
1
0
49
3w
preferredImageDynamicRange is not marked as being available only for iOS 17 and above.
open var isAnimating: Bool { get } /// The preferred treatment to use for HDR images. By default the image view will defer to the value from its traitCollection. open var preferredImageDynamicRange: UIImage.DynamicRange /// The resolved treatment to use for HDR images. open var imageDynamicRange: UIImage.DynamicRange { get } This attribute is not marked as being applicable only in iOS 17+ versions. When viewing the UIImageView code in Xcode, the @available(iOS 17.0, *) annotation was not added, which resulted in successful compilation but caused a crash on iOS 16 devices.
3
0
86
3w
Core Data + CKSyncEngine with Swift 6 — concurrency, Sendable, and best practices validation
Hi everyone, I’ve been working on migrating my app (SwimTimes, which helps swimmers track their times) to use Core Data + CKSyncEngine with Swift 6. After many iterations, forum searches, and experimentation, I’ve created a focused sample project that demonstrates the architecture I’m using. The good news: 👉 I believe the crashes I was experiencing are now solved, and the sync behavior is working correctly. 👉 The demo project compiles and runs cleanly with Swift 6. However, before adopting this as the final architecture, I’d like to ask the community (and hopefully Apple engineers) to validate a few critical points, especially regarding Swift 6 concurrency and Core Data contexts. Architecture Overview Persistence layer: Persistence.swift sets up the Core Data stack with a main viewContext and a background context for CKSyncEngine. Repositories: All Core Data access is abstracted into repository classes (UsersRepository, SwimTimesRepository), with async/await methods. SyncEngine: Wraps CKSyncEngine, handles system fields, sync tokens, and bridging between Core Data entities and CloudKit records. ViewModels: Marked @MainActor, exposing @Published arrays for SwiftUI. They never touch Core Data directly, only via repositories. UI: Simple SwiftUI views bound to the ViewModels. Entities: UserEntity → represents swimmers. SwimTimeEntity → times linked to a user (1-to-many). Current Status The project works and syncs across devices. But there are two open concerns I’d like validated: Concurrency & Memory Safety Am I correctly separating viewContext (main/UI) vs. background context (used by CKSyncEngine)? Could there still be hidden risks of race conditions or memory crashes that I’m not catching? Swift 6 Sendable Compliance Currently, I still need @unchecked Sendable in the SyncEngine and repository layers. What is the recommended way to fully remove these workarounds and make the code safe under Swift 6’s stricter concurrency rules? Request Please review this sample project and confirm whether the concurrency model is correct. Suggest how I can remove the @unchecked Sendable annotations safely. Any additional code improvements or best practices would also be very welcome — the intention is to share this as a community resource. I believe once finalized, this could serve as a good reference demo for Core Data + CKSyncEngine + Swift 6, helping others migrate safely. Environment iOS 18.5 Xcode 16.4 macOS 15.6 Swift 6 Sample Project Here is the full sample project on GitHub: 👉 [https://github.com/jarnaez728/coredata-cksyncengine-swift6] Thanks a lot for your time and for any insights! Best regards, Javier Arnáez de Pedro
3
0
400
4w
How To Position Controls With SwiftUI
I am coming from C#, where Forms and Controls are placed similar to Swift Storyboards. I have been trying to learn Storyboards, but keep running across tutorials regarding SwiftUI, and Storyboard examples are few. So the question becomes, "how do I position controls on a Form using SwiftUI?" See the example below. I have run across many videos that use either horizontal or vertical positioning of controls, but these examples are usually very simple, with items occupying only the center portion of the screen. I get stuck on examples that are more complicated. The example below only shows the controls for the upper part of a Form, with some type of textbox (Viewform) below making up the rest of the Form. How does one make more complicated placement of controls with SwiftUI?
10
0
357
4w
IPad OS 16.1, Playgrounds and input fields
I have installed the latest beta on my iPad , iPadOS 16.1 (20B5050f) On running in app in Playgrounds that has a TextField, external keyboard input do not seem to be working. Tapping on the Text field inserts the cursor but no text can be entered on my external keyboard. (TextEditor field also do not work) Tested with both a Smart Keyboard and a Magic Keyboard. The keyboard works to enter the code in playgrounds, so it is not a keyboard connection issue. Disconnecting the keyboard, the onscreen keyboard is displayed and works correctly. Is this a Playgrounds issue or an iPadOS 16.1 issue or a compatibility issue with Playgrounds & iPadOS 16.1 ? import SwiftUI struct ContentView: View {     @State var field: String = "Test input"          var body: some View {         VStack {             Image(systemName: "globe")                 .imageScale(.large)                 .foregroundColor(.accentColor)             Text("Hello, world!")             TextField("", text: $field)                 .frame(height: 100)         }     } }
3
0
1.6k
Sep ’25
View title misaligned after compiling with Xcode 26
After compiling with Xcode 26, my UIKit view's title appears hugging the screen on the left when run on iOS 16-18 (as shown in the image below). It's fine when run on iOS 26, but not older iOS versions. When I compile the same code with Xcode 16.4, the title aligns with the table rows. Has anyone else seen this? Is this a bug in the frameworks or is there something I could do to resolve?
1
0
87
Sep ’25
Crashes launching app from Camera control button
I'm using the LockedCameraCaptureExtension to launch my Camera app from the camera button. Some of our users report our app crashing a few seconds after being launch from the camera button. The call stack is something inside BoardServices [BSServicesConfiguration activateXPCService] I'm not sure how to investigate or fix this, anyone else having the same issue? Basically in my LockedCameraCaptureExtension when it loads I just call openApplication on the LockedCameraCaptureSession to launch into my app. @main struct captureExtension: LockedCameraCaptureExtension { var body: some LockedCameraCaptureExtensionScene { LockedCameraCaptureUIScene { session in Button(action: { Task { await openCamera(session: session) } }, label: { Text("Open Camera") }) .buttonStyle(PlainButtonStyle()) .task { await openCamera(session: session) } } } private func openCamera(session: LockedCameraCaptureSession) async { try? await session.openApplication(for: NSUserActivity(activityType: "com.mycompany.camera")) } }
0
0
50
Sep ’25
ScrollView paging position is off in iOS 26
Hi everyone, I have the following issue that I have tried to tweak every possible modifier of ScrollView and still got the same result in iOS 26. Description: Create a SwiftUI ScrollView with scrollTargetBehavior of paging, also create a bottom UI view below the ScrollView. If the starting index is not 0, the position of current page will be off with part of previous page shown above it. It only happens on iOS 26, not on iOS 18. Also if bottom UI view (text view in this case) is removed, it also works fine. I want to see if there is a solution for it or it's an iOS 26 bug. Thanks! import SwiftUI struct ContentView: View { @State private var currentPageIndex: Int? = 3 var body: some View { VStack { scrollView Text("Bottom Bar") .frame(maxWidth: .infinity) .frame(height: 80) .background(.red) } .background(.black) } @ViewBuilder var scrollView: some View { VerticalPagerView( currentPageIndex: $currentPageIndex, itemCount: 10, content: Array(0...9).map { index in content(for: index) } ) } @ViewBuilder private func content(for index: Int) -> some View { // Empty view with random background color Color( red: Double((index * 25 + 0) % 255) / 255.0, green: Double((index * 25 + 80) % 255) / 255.0, blue: Double((index * 25 + 160) % 255) / 255.0 ) } } struct VerticalPagerView<Content: View>: View { @Binding private var currentPageIndex: Int? private let itemCount: Int private let content: [Content] init( currentPageIndex: Binding<Int?>, itemCount: Int, content: [Content] ) { self._currentPageIndex = currentPageIndex self.itemCount = itemCount self.content = content } var body: some View { GeometryReader { geometryReader in ScrollViewReader { reader in ScrollView(.vertical) { LazyVStack(spacing: 0) { ForEach(0 ..< itemCount, id: \.self) { index in content[index] .id(index) .containerRelativeFrame(.vertical, alignment: .center) .clipped() } } .frame(minHeight: geometryReader.size.height) .scrollTargetLayout() } .scrollIndicators(.hidden) .onAppear { guard let currentPageIndex = currentPageIndex else { return } reader.scrollTo(currentPageIndex, anchor: .center) } } .scrollPosition(id: $currentPageIndex, anchor: .center) .ignoresSafeArea() .scrollTargetBehavior(.paging) .onChange(of: currentPageIndex) { oldIndex, newIndex in } } } }
0
2
162
Sep ’25
App Crashes on Paper Selection After Background Printer Connection
Description: 1. When initiating the print flow via UIPrintInteractionController, and no printer is initially connected, iOS displays all possible paper sizes in the paper selection UI. However, if a printer connects in the background after this view is shown, the list of paper sizes does not automatically refresh to reflect only the options supported by the connected printer. 2. If the user selects an incompatible paper size (one not supported by the printer that has just connected), the app crashes due to an invalid configuration. Steps to Reproduce: Launch the app and navigate to the print functionality. Tap the Print button to invoke UIPrintInteractionController. At this point, no printer is yet connected. iOS displays all available paper sizes. While the paper selection UI is visible, the AirPrint-compatible printer connects in the background. Without dismissing the controller, the user selects a paper size (e.g., one that is not supported by the printer). The app crashes. Expected Result: App should not crash Once the printer becomes available (connected in the background), the paper size options should refresh automatically. The list should be filtered to only include sizes that are compatible with the connected printer. This prevents the user from selecting an invalid option, avoiding crashes. Actual Result: App crashes The paper size list remains unfiltered. The user can still select unsupported paper sizes. Selecting an incompatible option causes the app to crash, due to a mismatch between UI selection and printer capability. Demo App Crash : https://drive.google.com/file/d/19PV02wzOJhc2DYI6kAe-uxHuR1Qg15Bu/view?usp=sharing Apple Files App Crash: https://drive.google.com/file/d/1flHKuU_xaxHSzRun1dYlh8w7nBPJZeRb/view?usp=sharing
2
0
109
Sep ’25
SwiftUI - AsyncImage causing massive tmp folder?
So I have a perplexing situation. I'm loading multiple SwiftUI AsyncImages according to spec (see code below). For some reason, my 1MB app has over 400+ MBs of documents & data. When I view the app's container, I can see that it is caused by a massive number of the images as .tmp files in the "tmp" folder all starting with the name "CFNetworkDownload". It seems that every time an image is loaded, it's stored in here, but does not delete. This makes the app get bigger every time it's opened. What can I do about this issue? Thanks so much! (P.S. I've tried to condense my code down as much as possible for readability, but there's a few files included because I'm not sure where the problem lies.) Main app Swift file: @main struct MyApp: App { let monitor = NWPathMonitor() @State private var isConnected = true var body: some Scene { monitor.pathUpdateHandler = { path in if path.status == .satisfied { if !isConnected { isConnected.toggle() } } else { if isConnected { isConnected.toggle() } } } let queue = DispatchQueue(label: "Monitor") monitor.start(queue: queue) return WindowGroup { isConnected ? AnyView(ContentView()) : AnyView(ContentViewFailed()) } } } The ContentView that's loaded inside the above WindowGroup: struct ContentView: View { var body: some View { TabView { HomeView() .tabItem { Image(systemName: "house.fill") Text("Home") } . . . } } } And finally, the HomeView where the images are being loaded: struct HomeView: View { var body: some View { let urlString = "https://www.example.com/Home.json" if let url = URL(string: urlString) { if let data = try? Data(contentsOf: url) { do { items = try JSONDecoder().decode([Item].self, from: data) } catch { print(error) } } } return NavigationView { List { ScrollView { VStack(alignment: .leading) { ZStack { VStack(alignment: .leading) { Spacer() HStack { AsyncImage(url: URL(string: "https://www.example.com/images/example.png")) { image in image .resizable() .aspectRatio(contentMode: .fill) .shadow(color: Color(red: 0, green: 0, blue: 0, opacity: 0.25), radius: 1) } placeholder: { ProgressView() .progressViewStyle(.circular) } .frame(width: 202, height: 100) } . . . } } } } } } } } I really appreciate your time. Not sure if this could just be a bug with AsyncImage itself.
2
1
1.4k
Sep ’25
Sharing file creates new UIScene each time, how to prevent this
I have an App which supports multiple windows on the iPad. The App can receive URLs from other Apps (via application.openURL()) and also files via "share sheet" (via UIActivityViewController). When receiving a URL from another App the delegate method scene(_ scene: UIScene, openURLContexts URLContexts: Set) will be called on an existing UIScene, however when a file is received through the share sheet from another App, a new UIScene is created and therefore also a new window (eg the delegates application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) and scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) are called). In both cases I do get the URL and file just fine, however I do not want to get new UIScenes and windows created when receiving a file via share sheet. How can I prevent to get a new UIScene or window? The received files should be used in the existing windows and should not create new ones.
0
0
63
Sep ’25