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
876
Oct ’25
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.
0
0
9
12h
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
119
1d
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
83
2d
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
27
3d
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
87
4d
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
38
4d
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
4d
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
127
5d
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
541
1w
Announcing the Swift Student Challenge 2026
Announcing the Swift Student Challenge 2026 Every year, Apple’s Swift Student Challenge celebrates the creativity and ingenuity of student developers from around the world, inviting them to use Swift and Xcode to solve real-world problems in their own communities and beyond. Learn more → https://developer.apple.com/swift-student-challenge/ Submissions for the 2026 challenge will open February 6 for three weeks, and students can prepare with new Develop in Swift tutorials and Meet with Apple code-along sessions. The Apple Developer team is here is to help you along the way - from idea to app, post your questions at any stage of your development here in this forum board or be sure to add the Swift Student Challenge tag to your technology-specific forum question. Your designs. Your apps. Your moment.
6
3
1k
1w
What would you say to someone who is new to iOS?
Hello everyone! I'm a newly graduated Computer Engineer living in Türkiye. I've been developing my skills in the iOS field for a while now. But sometimes I get lost and don't know what to do. I've just joined this community and have a request for you. I'd be very grateful if you could share your own advice, experiences you've had along the way, and how you successfully overcame them. I'm open to all kinds of positive or negative feedback. Self-improvement is paramount to me.
2
0
216
1w
FPS not able to do > 30 fps for Pro and ProMax models only
We’re developing an AVFoundation-based video recording app (4K @ 60 fps required for biomechanical analysis). On most devices this works perfectly (iPhone 12/14/15/16 non-Pro models), but on several iPhone Pro models (12 Pro, 13 Pro, 14 Pro, 15 Pro/Pro Max), we consistently get 4K 30 fps recordings—even when the device should support 4K 60 fps on the wide-angle camera. What we observe We configure the session for .hd4K3840x2160. We iterate through AVCaptureDevice.formats and select formats that: have 3840×2160 resolution support ≥60 fps (videoSupportedFrameRateRanges) On some Pro devices, this format search returns no results, even though: The Camera app records 4K60 fine. External references list the wide camera as 4K60 capable. The fallback becomes the device's default 4K30 format, so final files are 3840×2160 @ 30 fps. This happens immediately on app launch (not after heating), so not thermal-related. What we’ve tried Force selecting .builtInWideAngleCamera instead of dual/triple cameras. Disabling HDR (videoHDREnabled = false). Disabling low-light boost. Allowing 59.94 fps formats (in case exact 60.0 isn’t exposed). Logging all videoSupportedFrameRateRanges per format. What we’re seeing in logs On affected Pro devices, the capture device reports only 4K formats with maxFrameRate ≈ 30 fps, despite the hardware being able to do 4K60. Main question Has anyone encountered cases where 4K60 formats are available in the Camera app but not exposed through AVFoundation, especially on Pro models or multi-camera devices? Could HEVC/HDR capability or multi-camera constraints be preventing certain formats from appearing? Are there known conditions where 4K60 formats are hidden unless specific device configuration is applied? Any guidance on reliably locking 4K60 on iPhone Pro models via AVFoundation would be hugely appreciated.
0
0
245
1w
How to Implement Screen Mirroring in iOS for Google TV?
I am developing an iOS application that supports screen mirroring to Google TV (or Chromecast with Google TV). My goal is to mirror the iPhone/iPad screen in real time to a Google TV device. What I Have Tried So Far I have explored multiple approaches but haven't found a direct way to achieve low-latency screen mirroring. Here are some of my findings: Google Cast SDK: Google Cast SDK is primarily designed for casting media (videos, images, audio) rather than real-time mirroring. It supports custom receiver applications, but there are no direct APIs for full screen mirroring. Casting a recorded video is possible, but it introduces latency and is not real-time. ReplayKit for Screen Capture: RPScreenRecorder.shared().startCapture(handler: ...) allows capturing the iPhone screen as a video stream. However, sending this stream to Google TV in real time is a challenge. I could potentially encode the video as HLS and stream it, but the delay is significant. RTSP/UDP Streaming: Some third-party libraries support RTSP/UDP streaming for real-time screen sharing. Google TV does not natively support RTSP, making this approach difficult. My Questions: Is it possible to achieve real-time screen mirroring on Google TV using Google Cast SDK? Does Google TV support WebRTC or any low-latency streaming protocol that can be used from iOS? Are there any alternative approaches to mirror an iOS screen to Google TV with minimal latency? I would appreciate any guidance, code examples, or references to relevant documentation.
1
1
595
1w
UISplitViewController.showDetailViewController() not working in iPhone version.
Since updating to Tahoe and Xcode 26 I have found that the UISplitViewController.showDetailViewController() is not working in the iPhone version of my app (it is a universal app). I'm just trying to show a detail view after a tap on a UITableView item. The iPad versions are all working correctly. Has anyone else experienced this or have any advice about what may have changed? Thanks in advance.
1
0
150
1w
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.
3
0
127
1w
Unwanted animations appear on UIButton (iOS 26)
After the iOS 26 update, unwanted animations appear on UIButton. I'm using the attributedTitle property of UIButton.Configuration to change the button's text, and an animation appears after iOS 26. (It's unclear whether it's after iOS 26.0 or iOS 26.1, but it likely started with 26.1.) The peculiar thing is that the animation only starts appearing on buttons that have been pressed once. I tried using UIView.performWithoutAnimation and CATransaction's begin(), setDisableActions(true), commit(), but it didn't work. How should I solve this? Below is the code for changing the button's text. func updateTitle() { let keys = type.keys if keys.count == 1 { guard let key = keys.first else { return } if key.count == 1 { if Character(key).isLowercase { self.configuration?.attributedTitle = AttributedString(key, attributes: AttributeContainer([.font: UIFont.systemFont(ofSize: 24, weight: .regular), .foregroundColor: UIColor.label])) } else if Character(key).isUppercase { self.configuration?.attributedTitle = AttributedString(key, attributes: AttributeContainer([.font: UIFont.systemFont(ofSize: 22, weight: .regular), .foregroundColor: UIColor.label])) } else { self.configuration?.attributedTitle = AttributedString(key, attributes: AttributeContainer([.font: UIFont.systemFont(ofSize: 22, weight: .regular), .foregroundColor: UIColor.label])) } } else { self.configuration?.attributedTitle = AttributedString(key, attributes: AttributeContainer([.font: UIFont.systemFont(ofSize: 18, weight: .regular), .foregroundColor: UIColor.label])) } } else { let joined = keys.joined(separator: "") self.configuration?.attributedTitle = AttributedString(joined, attributes: AttributeContainer([.font: UIFont.systemFont(ofSize: 22, weight: .regular), .foregroundColor: UIColor.label])) } }
1
0
161
1w