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

Posts under Swift tag

200 Posts

Post

Replies

Boosts

Views

Activity

Programming Languages Resources
This topic area is about the programming languages themselves, not about any specific API or tool. If you have an API question, go to the top level and look for a subtopic for that API. If you have a question about Apple developer tools, start in the Developer Tools & Services topic. For Swift questions: If your question is about the SwiftUI framework, start in UI Frameworks > SwiftUI. If your question is specific to the Swift Playground app, ask over in Developer Tools & Services > Swift Playground If you’re interested in the Swift open source effort — that includes the evolution of the language, the open source tools and libraries, and Swift on non-Apple platforms — check out Swift Forums If your question is about the Swift language, that’s on topic for Programming Languages > Swift, but you might have more luck asking it in Swift Forums > Using Swift. General: Forums topic: Programming Languages Swift: Forums subtopic: Programming Languages > Swift Forums tags: Swift Developer > Swift website Swift Programming Language website The Swift Programming Language documentation Swift Forums website, and specifically Swift Forums > Using Swift Swift Package Index website Concurrency Resources, which covers Swift concurrency How to think properly about binding memory Swift Forums thread Other: Forums subtopic: Programming Languages > Generic Forums tags: Objective-C Programming with Objective-C archived documentation Objective-C Runtime documentation Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
0
0
890
Oct ’25
Need Inputs on Which Extension to Use
Hi all, I have a working macOS (Intel) system extension app that currently uses only a Content Filter (NEFilterDataProvider). I need to capture/log HTTP and HTTPS traffic in plain text, and I understand NETransparentProxyProvider is the right extension type for that. For HTTPS I will need TLS inspection / a MITM proxy — I’m new to that and unsure how complex it will be. For DNS data (in plain text), can I use the same extension, or do I need a separate extension type such as NEPacketTunnelProvider, NEFilterPacketProvider, or NEDNSProxyProvider? Current architecture: Two Xcode targets: MainApp and a SystemExtension target. The SystemExtension target contains multiple network extension types. MainApp ↔ SystemExtension communicate via a bidirectional NSXPC connection. I can already enable two extensions (Content Filter and TransparentProxy). With the NETransparentProxy, I still need to implement HTTPS capture. Questions I’d appreciate help with: Can NETransparentProxy capture the DNS fields I need (dns_hostname, dns_query_type, dns_response_code, dns_answer_number, etc.), or do I need an additional extension type to capture DNS in plain text? If a separate extension is required, is it possible or problematic to include that extension type (Packet Tunnel / DNS Proxy / etc.) in the same SystemExtension Xcode target as the TransparentProxy? Any recommended resources or guidance on TLS inspection / MITM proxy setup for capturing HTTPS logs? There are multiple DNS transport types — am I correct that capturing DNS over UDP (port 53) is not necessarily sufficient? Which DNS types should I plan to handle? I’ve read that TransparentProxy and other extension types (e.g., Packet Tunnel) cannot coexist in the same Xcode target. Is that true? Best approach for delivering logs from multiple extensions to the main app (is it feasible)? Or what’s the best way to capture logs so an external/independent process (or C/C++ daemon) can consume them? Required data to capture (not limited to): All HTTP/HTTPS (request, body, URL, response, etc.) DNS fields: dns_hostname, dns_query_type, dns_response_code, dns_answer_number, and other DNS data — all in plain text. I’ve read various resources but remain unclear which extension(s) to use and whether multiple extension types can be combined in one Xcode target. Please ask if you need more details. Thank you.
4
0
152
3h
App Crash in GameController when accessing GCKeyboard.coalesced on iPad
We are developing a hybrid iOS app where Angular content is rendered inside a WKWebView, hosted by a native Swift application. We use the GameController framework to detect whether an external Bluetooth keyboard is connected to an iPad. The following code is executed when the app enters the foreground and also when requested by the web layer: func keyboardStatusHandler(){ let isKeyboardConnected = GCKeyboard.coalesced != nil if(!isKeyboardConnected){ //sent status to Angular } else { //sent status to Angular } } Crash details We are seeing intermittent crashes on iPad with the following stack trace: Crashed: GCDeviceSession.HID 0 libobjc.A.dylib 0x7db8 objc_retain_x8 + 16 1 libsystem_blocks.dylib 0xfb8 void HelperBase<ExtendedInline>::copyCapture<(HelperBase<ExtendedInline>::BlockCaptureKind)3>(unsigned int) + 48 2 libsystem_blocks.dylib 0xbc4 HelperBase<GenericInline>::copyBlock(Block_layout*, Block_layout*) + 108 3 libsystem_blocks.dylib 0xc94 _call_copy_helpers_excp + 60 4 libsystem_blocks.dylib 0xef8 _Block_copy + 412 5 libdispatch.dylib 0x1a70 _dispatch_Block_copy + 32 6 libdispatch.dylib 0x792c dispatch_async + 56 7 libdispatch.dylib 0x792c dispatch_channel_async + 56 8 GameController 0xea6dc -[GCKeyboardInput _handleKeyboardEvent:] + 324 9 GameController 0x22508 __53-[_GCKeyboardEventHIDAdapter initWithSource:service:]_block_invoke + 376 10 GameController 0x11d30 -[_GCHIDEventSubject publishHIDEvent:] + 268 11 GameController 0xb79cc __40-[_GCHIDEventUIKitClient initWithQueue:]_block_invoke_3 + 44 12 libdispatch.dylib 0x1b584 _dispatch_client_callout + 16 13 libdispatch.dylib 0x12088 _dispatch_async_and_wait_invoke_and_complete_recurse + 272 14 libdispatch.dylib 0x8448 _dispatch_async_and_wait_f + 108 15 GameController 0xb7984 __40-[_GCHIDEventUIKitClient initWithQueue:]_block_invoke_2 + 132 16 GameController 0xb746c __48-[__GCHIDEventUIKitClient _initWithApplication:]_block_invoke + 256 17 UIKitCore 0x11fd394 __61-[UIEventFetcher _setHIDGameControllerEventObserver:onQueue:]_block_invoke_3 + 40 18 libdispatch.dylib 0x1aac _dispatch_call_block_and_release + 32 19 libdispatch.dylib 0x1b584 _dispatch_client_callout + 16 20 libdispatch.dylib 0xa2d0 _dispatch_lane_serial_drain + 740 21 libdispatch.dylib 0xadac _dispatch_lane_invoke + 388 22 libdispatch.dylib 0x151dc _dispatch_root_queue_drain_deferred_wlh + 292 23 libdispatch.dylib 0x14a60 _dispatch_workloop_worker_thread + 540 24 libsystem_pthread.dylib 0xa0c _pthread_wqthread + 292 25 libsystem_pthread.dylib 0xaac start_wqthread + 8 Observed scenarios Crash occurs when the app transitions from background to foreground Crash also occurs when the Angular layer requests keyboard status, triggering the same code path Questions Has anyone encountered crashes related to GCKeyboard.coalesced or GCKeyboardInput like this? Are there known issues with the GameController framework when querying keyboard state during app lifecycle transitions? Is there a recommended or safer way to detect external keyboard connection status on iPad (especially when using WKWebView)? Any insights, known platform issues, or suggested workarounds would be greatly appreciated. Thanks!
4
0
177
10h
The latest iPhone model cannot retrieve the Wi-Fi information it has connected to.
The latest iPhone model is unable to retrieve the Wi-Fi information it has connected to. The phone's operating system is iOS 26.1, and location permission has also been granted. "Access Wi-Fi Information" is also configured in the same way The following is the code I used to obtain Wi-Fi information: func getCurrentWiFiInfo() -> String? { guard let interfaces = CNCopySupportedInterfaces() as? [String] else { return nil } for interface in interfaces { guard let info = CNCopyCurrentNetworkInfo(interface as CFString) as? [String: Any] else { continue } if let ssid = info[kCNNetworkInfoKeySSID as String] as? String, !ssid.isEmpty { return ssid } } return nil }
0
0
76
11h
Game Center fetchSavedGames sometimes returns empty list of games, although it works correctly on the next tries
I have implemented the Game Center for authentication and saving player's game data. Both authentication and saving player's data works correctly all the time, but there is a problem with fetching and loading the data. The game works like this: At the startup, I start the authentication After the player successfully logs in, I start loading the player's data by calling fetchSavedGames method If a game data exists for the player, I receive a list of SavedGame object containing the player's data The problem is that after I uninstall the game and install it again, sometimes the SavedGame list is empty(step 3). But if I don't uninstall the game and reopen the game, this process works fine. Here's the complete code of Game Center implementation: class GameCenterHandler { public func signIn() { GKLocalPlayer.local.authenticateHandler = { viewController, error in if let viewController = viewController { viewController.present(viewController, animated: false) return } if error != nil { // Player could not be authenticated. // Disable Game Center in the game. return } // Auth successfull self.load(filename: "TestFileName") } } public func save(filename: String, data: String) { if GKLocalPlayer.local.isAuthenticated { GKLocalPlayer.local.saveGameData(Data(data.utf8), withName: filename) { savedGame, error in if savedGame != nil { // Data saved successfully } if error != nil { // Error in saving game data! } } } else { // Error in saving game data! User is not authenticated" } } public func load(filename: String) { if GKLocalPlayer.local.isAuthenticated { GKLocalPlayer.local.fetchSavedGames { games, error in if let game = games?.first(where: {$0.name == filename}){ game.loadData { data, error in if data != nil { // Data loaded successfully } if error != nil { // Error in loading game data! } } } else { // Error in loading game data! Filename not found } } } else { // Error in loading game data! User is not authenticated } } } I have also added Game Center and iCloud capabilities in xcode. Also in the iCloud section, I selected the iCloud Documents and added a container. I found a simillar question here but it doesn't make things clearer.
1
0
769
17h
ITMS-90426: Invalid Swift Support - The SwiftSupport folder is missing. Rebuild your app using the current public (GM) version of Xcode and resubmit it
We are getting the above mentioned error while uploading to TestFlight. We have used a Swift Class to request for the Age Range via DeclaredAgeRange Framework. We have exposed Swift class and a helper function to be available in Objective-C layer. We have enabled the following build settings SWIFT_OBJC_INTERFACE_HEADER_NAME = "Common-Swift.h"; SWIFT_OBJC_BRIDGING_HEADER = "Common-Bridging-Header.h "; ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES Also we are compiling the application using latest available Xcode release 17C52 Is there anything else we need to do to resolve the error?
1
0
59
19h
Controlling UIDesignRequiresCompatibility via Remote Config
Hello, I am currently in the process of gradually adding support for LiquidGlass to my app. The transition is taking place incrementally, i.e., new screens and minor features are gradually being adapted to the new design and already deployed. Currently, the old design is still active via the feature flag UIDesignRequiresCompatibility, as the existing UI should remain locked for the public app store version until the transition is complete. My challenge is as follows: I would like to work with the new LiquidGlass design during development without having to manually change the UIDesignRequiresCompatibility flag with each deployment. Ideally, I am looking for a solution where: • the new design is only activated for me (e.g., specific account or specific devices) • the old design remains active for all other users • the App Store version can be delivered unchanged So my question is: Is it possible to control UIDesignRequiresCompatibility via remote config or server-side logic in order to activate the new design specifically for certain users or devices? I have observed similar behavior on WhatsApp—two devices with the same app version, but only one shows the new design. This suggests server-side or remote config-based control. Do you have any experience or recommendations on how to implement something like this cleanly? Kind regards Heinz
1
0
22
19h
AgeRangeService system prompt does not allow displaying upper age threshold (e.g. 18+)
We are using AgeRangeService.requestAgeRange(ageGates:in:) with an age gate of 18 to verify adult users. The system prompt always displays the lower-bound wording (“17 or Younger”), even when the app’s requirement is to verify users who are 18 or older. We understand the UI is system-controlled; however, this wording causes confusion for users, QA, and product teams, as it appears to indicate a child-only flow even when requesting adult verification. Based on the demonstration video, it appears that they have another more coherent message. In Apple's example, it is different, and it is correct that we need to specify 18 years or older in the implementation. A little more context might be helpful, but we are creating a kind of wrapper with React Native that receives that value as a parameter, which is 18.
2
0
99
20h
During the process of uploading a large file, I moved it to the trash can. How can I directly interrupt this upload process
I am currently encountering a problem: during the process of uploading a large file, I have moved the file that was not successfully uploaded to the trash can. These two operations have been tested to be serial (triggering the 'create Item' callback first, followed by the 'modify Item' callback), which means that the file must be uploaded before it can be moved to the recycle bin (which can also result in the file being stored in the cloud recycle bin). I want to implement: directly interrupt this upload process and then do not complete the upload. How can I achieve this? Please help me. Thank you
0
0
21
1d
Is Xcode's predictive code completion model has some censoring?
It seems Xcode's predictive code completion model is censored. Specifically, when typing the word "torrent," the model stops working completely. It doesn't matter whether the word is written directly in the code or in a comment. It could also be part of another word, such as "qBittorrent." In either case, the model stops working. Reproducing this issue is fairly simple. Create a Swift file and type the word "torrent." The model will stop generating code. Xcode Version 26.2 (17C52) Predictive Code Completion Model: [com.apple.fm.code.generate_small_v2.base: 700.0.81600.13.202379,0] [com.apple.fm.code.generate_safety_guardrail.base: 1.6.81619.13.202072,0] [com.apple.gm.safety_deny.input.code_intelligence.base: 32025010.20251009.91600.100.1651,0] [com.apple.gm.safety_deny.output.code_intelligence.base: 32025010.20251009.91600.100.1651,0] (Installed)
0
0
74
1d
StoreKit 2: Delayed Transaction and Entitlement Updates After Promo Code Subscription Redemption
I’m implementing a subscription purchase flow using promo code redemption via an external App Store URL. Flow: User taps “Purchase” in the app (spinner shown) App opens the promo redemption URL (apps.apple.com/redeem) User completes redemption in the App Store User returns to the app The app must determine whether the subscription was purchased within a reasonable time window The app listens to Transaction.updates and also checks Transaction.currentEntitlements when the app returns to the foreground. Issue: After redeeming a subscription promo code via the App Store and returning to the app, the app cannot reliably determine whether the subscription was successfully purchased within a short, user-acceptable time window. In many cases, neither Transaction.updates nor Transaction.currentEntitlements reflects the newly redeemed subscription immediately after returning to the app. The entitlement may appear only after a significant delay, or not within a 60-second timeout at all, even though the promo code redemption succeeded. Expected: When the user returns to the app after completing promo code redemption, StoreKit 2 should report the updated subscription entitlement shortly thereafter (e.g. within a few seconds) via either Transaction.updates or Transaction.currentEntitlements. Below is the minimal interactor used in the sample project. The app considers the purchase successful if either a verified transaction for the product is received via Transaction.updates, or the product appears in Transaction.currentEntitlements when the app returns to the foreground. Otherwise, the flow fails after a 60-second timeout. Questions: Is this entitlement propagation delay expected when redeeming promo codes through the App Store? Is there a recommended API or flow for immediately determining whether a subscription has been successfully redeemed? Is there a more reliable way to detect entitlement changes after promo code redemption without triggering user authentication prompts (e.g., from AppStore.sync())? import UIKit import StoreKit final class PromoPurchaseInteractor { private let timeout: TimeInterval = 60 private struct PendingOfferRedemption { let productId: String let completion: (Result<Bool, Error>) -> Void } private var pendingRedemption: PendingOfferRedemption? private var updatesTask: Task<Void, Never>? private var timeoutTask: Task<Void, Never>? enum DefaultError: Error { case generic case timeout } init() { NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self) updatesTask?.cancel() timeoutTask?.cancel() } func purchaseProduct(using offerUrl: URL, productId: String, completion: @escaping (Result<Bool, Error>) -> Void) { guard pendingRedemption == nil else { completion(.failure(DefaultError.generic)) return } pendingRedemption = PendingOfferRedemption(productId: productId, completion: completion) startPurchase(using: offerUrl) } @objc private func willEnterForeground() { guard let pendingRedemption = pendingRedemption else { return } startTimeoutObserver() Task { if await hasEntitlement(for: pendingRedemption.productId) { await MainActor.run { self.completePurchase(result: .success(true)) } } } } private func startPurchase(using offerURL: URL) { startTransactionUpdatesObserver() UIApplication.shared.open(offerURL) { [weak self] success in guard let self = self else { return } if !success { self.completePurchase(result: .failure(DefaultError.generic)) } } } private func completePurchase(result: Result<Bool, Error>) { stopTransactionUpdatesObserver() stopTimeoutObserver() guard let _ = pendingRedemption else { return } pendingRedemption?.completion(result) pendingRedemption = nil } private func startTransactionUpdatesObserver() { updatesTask?.cancel() updatesTask = Task { for await update in Transaction.updates { guard case .verified(let transaction) = update else { continue } await MainActor.run { [weak self] in guard let self = self, let pending = self.pendingRedemption, transaction.productID == pending.productId else { return } self.completePurchase(result: .success(true)) } await transaction.finish() } } } private func stopTransactionUpdatesObserver() { updatesTask?.cancel() updatesTask = nil } private func startTimeoutObserver() { guard pendingRedemption != nil else { return } timeoutTask?.cancel() timeoutTask = Task { try? await Task.sleep(nanoseconds: UInt64(timeout * 1_000_000_000)) await MainActor.run { [weak self] in self?.completePurchase(result: .failure(DefaultError.timeout)) } } } private func stopTimeoutObserver() { timeoutTask?.cancel() timeoutTask = nil } private func hasEntitlement(for productId: String) async -> Bool { for await result in Transaction.currentEntitlements { guard case .verified(let transaction) = result else { continue } if transaction.productID == productId { return true } } return false } }
0
0
32
2d
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)         }     } }
4
0
1.7k
3d
How to set the custom DNS with the Network client
We are facing a DNS resolution issue with a specific ISP, where our domain name does not resolve correctly using the system DNS. However, the same domain works as expected when a custom DNS resolver is used. On Android, this is straightforward to handle by configuring a custom DNS implementation using OkHttp / Retrofit. I am trying to implement a functionally equivalent solution in native iOS (Swift / SwiftUI). **Android Reference (Working Behavior) : ** val dns = DnsOverHttps.Builder() .client(OkHttpClient()) .url("https://cloudflare-dns.com/dns-query".toHttpUrl()) .bootstrapDnsHosts(InetAddress.getByName("1.1.1.1")).build() OkHttpClient.Builder().dns(dns).build() **Attempted iOS Approach ** I attempted the following approach : Resolve the domain to an IP address programmatically (using DNS over HTTPS) Connect directly to the resolved IP address Set the original domain in the Host HTTP header **DNS Resolution via DoH : ** func resolveDomain(domain: String) async throws -> String { guard let url = URL( string: "https://cloudflare-dns.com/dns-query?name=\(domain)&type=A" ) else { throw URLError(.badURL) } var request = URLRequest(url: url) request.setValue("application/dns-json", forHTTPHeaderField: "accept") let (data, _) = try await URLSession.shared.data(for: request) let response = try JSONDecoder().decode(DNSResponse.self, from: data) guard let ip = response.Answer?.first?.data else { throw URLError(.cannotFindHost) } return ip } **API Call Using Resolved IP : ** func callAPIUsingCustomDNS() async throws { let ip = try await resolveDomain(domain: "example.com") guard let url = URL(string: "https://\(ip)") else { throw URLError(.badURL) } let configuration = URLSessionConfiguration.ephemeral let session = URLSession( configuration: configuration, delegate: CustomURLSessionDelegate(originalHost: "example.com"), delegateQueue: .main ) var request = URLRequest(url: url) request.setValue("example.com", forHTTPHeaderField: "Host") let (_, response) = try await session.data(for: request) print("Success: \(response)") } **Problem Encountered ** When connecting via the IP address, the TLS handshake fails with the following error: Error Domain=NSURLErrorDomain Code=-1200 "A TLS error caused the secure connection to fail." This appears to happen because iOS sends the IP address as the Server Name Indication (SNI) during the TLS handshake, while the server’s certificate is issued for the domain name. **Custom URLSessionDelegate Attempt : ** class CustomURLSessionDelegate: NSObject, URLSessionDelegate { let originalHost: String init(originalHost: String) { self.originalHost = originalHost } func urlSession( _ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void ) { guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let serverTrust = challenge.protectionSpace.serverTrust else { completionHandler(.performDefaultHandling, nil) return } let sslPolicy = SecPolicyCreateSSL(true, originalHost as CFString) let basicPolicy = SecPolicyCreateBasicX509() SecTrustSetPolicies(serverTrust, [sslPolicy, basicPolicy] as CFArray) var error: CFError? if SecTrustEvaluateWithError(serverTrust, &error) { completionHandler(.useCredential, URLCredential(trust: serverTrust)) } else { completionHandler(.cancelAuthenticationChallenge, nil) } } } However, TLS validation still fails because the SNI remains the IP address, not the domain. I would appreciate guidance on the supported and App Store–compliant way to handle ISP-specific DNS resolution issues on iOS. If custom DNS or SNI configuration is not supported, what alternative architectural approaches are recommended by Apple?
1
0
129
6d
iOS doesn’t switch back to home router + socket connect failure in AP mode
In iOS AP-mode onboarding for IOT devices, why does the iPhone sometimes stay stuck on the device Wi-Fi (no internet) and fail to route packets to the device’s local IP, even though SSID is correct? Sub-questions to include: • Is this an iOS Wi-Fi auto-join priority issue? • Can AP networks become “sticky” after multiple joins? • How does iOS choose the active routing interface when Wi-Fi has no gateway? • Why does the packet never reach the device even though NWPath shows WiFi = satisfied?
1
0
96
1w
How to move focus across multiple textfields using arrow keys/enter key in iOS
Hi. I have an iOS application with multiple input fields. I have to design an experience such that whenever the user presses enter key on a textfield, it should move focus to the next input field. Similarly, consider a stack of 3 textfields, I want to cycle the focus as and when the user presses up/down arrow keys. Other platforms like Android, have this feature out-of-the-box. I wanted to understand if iOS also supports this kind of behavior. I know how to manually code such UX, but just wanted to confirm whether there is some inherent feature like on android which i can leverage? Thanks.
0
0
37
1w
SwiftUI - presentationDetents behaves incorrectly on iOS 16–18 but works correctly on iOS 26
I'm using a custom modifier called AutoSheetDetentModifier to automatically size a sheet based on its content. On iOS 26, it works as expected: the content height is measured correctly and the sheet shrinks to match that height. However, on iOS 16, 17 and 18, the same code doesn’t work. The content height is still measured, but the sheet does not reduce its height. Instead, the sheet remains larger and the content appears vertically centered. (Note that content() includes ScrollView) public struct AutoSheetDetentModifier: ViewModifier { @State private var height: CGFloat = 380 // default value to avoid bouncing public func body(content: Content) -> some View { content .modifier(MeasureHeightViewModifier(height: $height)) .presentationDetents([.height(height)]) } } public struct MeasureHeightViewModifier: ViewModifier { @Binding var height: CGFloat public func body(content: Content) -> some View { content .fixedSize(horizontal: false, vertical: true) .background( GeometryReader { geo -> Color in DispatchQueue.main.async { height = geo.size.height } return Color.clear } ) } } extension View { public func applyAutoSheetDetent() -> some View { self .modifier(AutoSheetDetentModifier()) } } public var body: some View { VStack { header() content() // includes ScrollView footer() } .background(Color.customGray) .applyAutoSheetDetent() } func content() -> some View { ScrollView { VStack { ForEach(items) { item in itemRow(item) } } } .frame(maxHeight: UIScreen.main.bounds.height * 0.7) } Screenshot from iOS 26 (working as expected): Screenshot from iOS 18 (not working): How can I make .presentationDetents(.height) shrink the sheet correctly on iOS 16–18, the same way it does on iOS 26?
1
0
104
1w
Questions about using the "UserNotification framework"
In macOS, how can I use UnmutableNotificationContent notifications to prevent the main window from activating when clicking the notification? code: import Cocoa import UserNotifications // Mandatory import for notification functionality class ViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Automatically request permissions and send a test notification when the view loads sendLocalNotification() } /// Core method to send a local notification func sendLocalNotification() { let notificationCenter = UNUserNotificationCenter.current() // 1. Request notification permissions (Mandatory step; user approval required) notificationCenter.requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] isGranted, error in guard let self = self else { return } // Handle permission request errors if let error = error { print("Permission request failed: \(error.localizedDescription)") return } // Exit if user denies permission if !isGranted { print("User denied notification permissions; cannot send notifications") return } // 2. Construct notification content using UNMutableNotificationContent let notificationContent = UNMutableNotificationContent() notificationContent.title = "Swift Notification Test" // Notification title notificationContent.subtitle = "macOS Local Notification" // Optional subtitle notificationContent.body = "This is a notification created with UNMutableNotificationContent" // Main content notificationContent.sound = .default // Optional notification sound (set to nil for no sound) notificationContent.badge = 1 // Optional app icon badge (set to nil for no badge) // 3. Set trigger condition (here: "trigger after 3 seconds"; can also use time/calendar triggers) let notificationTrigger = UNTimeIntervalNotificationTrigger( timeInterval: 3, // Delay in seconds repeats: false // Whether to repeat (false = one-time only) ) // 4. Create a notification request (requires a unique ID for later cancellation if needed) let notificationRequest = UNNotificationRequest( identifier: "SwiftMacNotification_001", // Unique identifier content: notificationContent, trigger: notificationTrigger ) // 5. Add the request to the notification center and wait for triggering notificationCenter.add(notificationRequest) { error in if let error = error { print("Notification delivery failed: \(error.localizedDescription)") } else { print("Notification added to queue; will trigger in 3 seconds") } } } } }
0
0
52
1w
Augmented Reality app unable to load the image from the camera
I have an app on the App Store for many years enabling users to post text into clouds in augmented reality. Yet last week abruptly upon installing the app on the iPhone the screen started going totally dark and a list of little comprehensible logs came up of the kind: ARSCNCompositor <0x300ad0e00>: ARSCNCompositor (0, 0) initialization failed. Matting is not set up properly. many times, then RWorldTrackingTechnique <0x106235180>: Unable to update pose [PredictorFailure] for timestamp 870.392108 ARWorldTrackingTechnique <0x106235180>: Unable to predict pose [1] for timestamp 870.392108 again several times and then: ARWorldTrackingTechnique <0x106235180>: SLAM error callback: Error Domain=Slam Error Code=7 "Non fatal error occurred due to significant drop in a IMU data" UserInfo={NSDescription=Non fatal error occurred due to significant drop in a IMU data, NSLocalizedFailureReason=SlamEngineNodeGroup Failure: IMU issue: gyro data stream verification failed [Significant data drop]. Failed on timestamp: 870.413247, Last known timestamp: 865.350198, Delta: 5.063049, System timestamp: 870.415781, Delta between system and frame: 0.002534. } and then again the pose issues several times. I hoped the new beta version would have solved the issue, but it was not the case. Unfortunately I do not know if that depends on the beta version or some other issue, given the app may be not installed on the Mac simulator.
16
2
2.2k
1w
Error Blocking Phone Numbers
In my case, when I try to block calls on iOS 26, the blocking doesn't occur; the scenarios seem intermittent. If I create two CallDirectory extensions, the first blocks the numbers, but the second doesn't. Interestingly, the extension marks the number as suspicious. There's also a case where, on iOS 26 on an iPhone 16 Pro, the functionality doesn't work at all. I'd like to know if there have been any changes to the use of CallKit in iOS 26, because users of my app on iOS 18 and below report successful blocking.
1
0
138
1w
Permission error occurs when I use setDefaultApplication(at:toOpen:completion:)
I'd like to set my macOS app written in Swift as default app when opening .mp4 file. I think I can do it with setDefaultApplication(at:toOpen:completion:). https://developer.apple.com/documentation/appkit/nsworkspace/3753002-setdefaultapplication However, permission error occurs when I use it. The error is: Error Domain=NSCocoaErrorDomain Code=256 "The file couldn’t be opened." UserInfo={NSUnderlyingError=0x6000031d0150 {Error Domain=NSOSStatusErrorDomain Code=-54 "permErr: permissions error (on file open)"}} I tried to give my app full-disk access, but it didn't work. I also tried to use setDefaultApplication(at:toOpenFileAt:completion:), then it works with no error, but it effects on only one file. What I want to do is to set my app as default app of all .mp4 files. How do I achieve this? My code is like below: let bundleUrl = Bundle.main.bundleURL NSWorkspace.shared.setDefaultApplication(at: bundleUrl, toOpen: .mpeg4Movie) { error in print(error) } Thank you.
3
2
545
1w