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
1.3k
Oct ’25
evaluateJavaScript callback is significantly slow on macOS 26.2 for iOS App on Mac
Hello, After upgrading to macOS 26.2, I’ve noticed a significant performance regression when calling evaluateJavaScript in an iOS App running on Mac (WKWebView, Swift project). Observed behavior On macOS 26.2, the callback of evaluateJavaScript takes around 3 seconds to return. This happens not only for: evaluateJavaScript("navigator.userAgent") but also for simple or even empty scripts, for example: evaluateJavaScript("") On previous macOS versions, the same calls typically returned in ~200 ms. Additional testing I created a new, empty Objective-C project with a WKWebView and tested the same evaluateJavaScript calls. In the Objective-C project, the callback still returns in ~200 ms, even on macOS 26.2. Question Is this a known issue or regression related to: iOS Apps on Mac, Swift + WKWebView, or behavioral changes in evaluateJavaScript on macOS 26.2? Any information about known issues, internal changes, or recommended workarounds would be greatly appreciated. Thank you. Test Code Swift class ViewController: UIViewController { private var tmpWebView: WKWebView? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setupUserAgent() } func setupUserAgent() { let t1 = CACurrentMediaTime() tmpWebView = WKWebView(frame: .zero) tmpWebView?.isInspectable = true tmpWebView?.evaluateJavaScript("navigator.userAgent") { [weak self] result, error in let t2 = CACurrentMediaTime() print("[getUserAgent] \(t2 - t1)s") self?.tmpWebView = nil } } } Test Code Objective-C - (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions { NSTimeInterval startTime = [[NSDate date] timeIntervalSince1970]; WKWebView *webView = [[WKWebView alloc] init]; dispatch_async(dispatch_get_main_queue(), ^{ [webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) { NSTimeInterval endTime = [[NSDate date] timeIntervalSince1970]; NSLog(@"[getUserAgent]: %.2f s", (endTime - startTime)); }]; }); }
6
2
1.2k
1h
iOS App never gets Bluetooth connection
I am developing an iOS App for a Bluetooth peripheral using SwiftUI with Swift 5 or 6. I have a few past attempts that got so far (connected to a peripheral), and some downloaded examples that connect to peripherals. Lately (last month or so), my current attempt never gets BleManager to start, and every attempt ends at my View that says 'please enable Bluetooth'. The Xcode console is totally blank with no print outputs. Coding Assistant suggested the init() in my @main structure could contain print("App initializing"), but even that never prints. Coding Assistant suggests: "• Open your project's Info.plist in Xcode. • Make sure UIApplicationSceneManifest is present and configured for SwiftUI, not referencing any storyboard. • Ensure UIMainStoryboardFile is not present (or blank)." but there is no info.plist because it is no longer required. Downloaded sample code runs and connects to peripherals, so Bluetooth is working on my iPhone and the Bluetooth device is accessible. My older attempts used to work, but now have the same problem. All attempts have "Enable Bluetooth to connect to Device" in the Privacy - Bluetooth Info.plist setting. Something is fundamentally wrong with many different code attempts. I have searched all the various settings for mention of SwiftUI or Storyboard, but not found them in working or failing projects. The downloaded code which works has minimum deployment iOS 14.0 and Swift Compiler Language Version Swift 5. My latest code attempt has minimum deployment iOS 16 and Swift 5. All code is target device iPhone (I am testing on iPhone 16e running iOS 26.2.1) and developing with Xcode 26.2 on MacBook Air M1 running the latest Tahoe. I do a Clean Build Folder before every test, and have tried re-starting both Mac and iPhone. How can my coding fail so spectacularly?
1
0
15
3h
UserDefaults.standard losing all data on iOS26
Hello. We are facing very silent and hardly replicable issue. All UserDefaults.standard data the application saved and was using to determine the state of app is lost and app behaves as if it was freshly installed. The issue always occurs only if we leave app on background for long time or if we manually swipe the app from the background apps. In case we swipe, this issue can occur in minutes, hours or up to 2 days by our latest testing. One important factor is that the app was developed using iOS18 in which issue never occured. Next it was being tested on iOS26 and it did everytime. Any currently available version of iOS26 reported this issue, all the way up to 26.2.1 (23C71). Our application is going through major upgrade of its whole lifecycle and services so it is possible this issue is caused by a bug in development as the production version does not report this issue neither on iOS26 of any version. The following list contains how we tried to fix this issue but none of which helped. App prewarming in the background (postpone all initialization including searching UserDefaults.standard for when isProtectedDataAvailable) Calling UserDefaults.standard.synchronize() everytime after saving data despite it is not recomended Built app using different SDK's (tested on iOS18 and iOS26 SDK) Distributed the app from local machine aswell as on TestFlight itself We searched through currently opened and closed issues for third-party libraries app uses regarding 'iOS26' and 'UserDefaults', especially those who were added recently with no success. The structure using which we save data into UserDefaults.standard did not change, we have only added few more settings to save through the lifecycle of the app after update. We estimate the overall increase is merely 30% more of what it used to be in previous version. Any ideas are much appreciated. We are considering to use different or fully custom ways to store app's settings.
1
0
32
5h
Using the Bloom filter tool to configure a URL filter Error 9
Hi, I tried to follow this guide: https://developer.apple.com/documentation/networkextension/filtering-traffic-by-url And this: https://github.com/apple/pir-service-example I already deploy the pir service on my server. And set the configuration on the app like this: { name = SimpleURLFilter identifier = xxxxx applicationName = SimpleURLFilter application = com.xxxx.SimpleURLFilter grade = 2 urlFilter = { Enabled = YES FailClosed = NO AppBundleIdentifier = com.mastersystem.SimpleURLFilter ControlProviderBundleIdentifier = com.xxxx.SimpleURLFilter.SimpleURLFilterExtension PrefilterFetchFrequency = 2700 pirServerURL = https://xxxxx/pir pirPrivacyPassIssuerURL = https://xxxxx/pir AuthenticationToken = AAAA pirPrivacyProxyFailOpen = NO pirSkipRegistration = NO } } But I got this error when I tried to enable the service on the app: Received filter status change: <FilterStatus: 'stopped' errorMessage: 'The operation couldn’t be completed. (NetworkExtension.NEURLFilterManager.Error error 9.)'> What does that error mean? And how to fix it?
1
0
42
11h
Camera layout within a sheet in iOS26
When inputting data within a sheet, I'm allowing the user to take a photo, so the camera is called and presents itself within a 2nd sheet, however the controls are centered within the iPhone's entire screen, cropping the top controls and not extending down to the bottom of the phone's screen. Any help on how to fix this?
1
0
45
1d
Whimsical tooltips behaviour in popover (Appkit)
In this app I use tooltips extensively. They work perfectly well, except in a popover where they may appear or not (just some flash and immediately disappear). In the popover there are 12 colour buttons, each with its own tracking area and 3 control buttons, with their tracking areas. Here when it works, hovering over "C" button or "Annuler" button: But then, when I move to another colour button, a few 2 or 3 may work, but most don't display their tooltip at all. I know that the tooltip is set because I replicate the message in a help line at the bottom of the screen and this line always update: Let messageForColor = "Choisir la couleur…" if button.isEnabled { // show tooltip button.toolTip = messageForColor } else { button.toolTip = nil } if button.isEnabled { // Shows helpline at the bottom of screen button.helpMessage = messageForColor } Maybe it comes from some useDefault (I modified NSInitialTool TipDelay and I'm not sure I have reset to the default value) I noted that if I wait for 10 seconds or so (keeping the popover opened), everything seems to work properly again. Just as if there was some lengthy initialisation going on. So questions: Is there a known issue of Tooltips in a popover ? Are there other parameters to set in userDefaults to avoid immediate disparition of the tooltip in popover ? How to reset the factory setting for the UserDefaults in the app ?
5
0
323
1d
Can I Upload a Single Screenshot Showing iPhone, iPad, and Mac Designs Together?
Hi everyone, I have a question about showcasing my Swift Student Challenge submission. My app includes layouts optimized for iPhone, iPad, and Mac, and I’d like to highlight that it works well across all three device sizes. Would it be acceptable to upload one combined screenshot that shows the same screen displayed on iPhone, iPad, and Mac side-by-side, to demonstrate the responsive design? Thanks in advance for any advice!
0
0
132
1d
Crash/Exception thrown in UITableView initialization stack
Hello, We are seeing an intermittent crash when initializing a base UITableView with Apple's [initWithFrame:style:] initializer. Crash stack: Role: Foreground OS Version: iOS 26.1 Exception Type: EXC_BREAKPOINT Exception Subtype: KERN_INVALID_ADDRESS EXC_BREAKPOINT: 0 libswiftCore.dylib +0x1358c0 _assertionFailure(_:_:file:line:flags:) 1 UIKitCore +0x1fdca0 0x188c26ca0 (0x188c26b20 + 384) 2 UIKitCore +0x1ffa60 0x188c28a60 (0x188c2890c + 340) 3 UIKitCore +0x2012d0 0x188c2a2d0 (0x188c2a1ec + 228) 4 UIKitCore +0x200f20 0x188c29f20 (0x188c29cac + 628) 5 UIKitCore +0x200428 0x188c29428 (0x188c29384 + 164) 6 UIKitCore +0x18af7f4 -[UITableMetricsAdapter _updateSharedSectionMetricsForListGeometry:] 7 UIKitCore +0x201da8 -[UITableMetricsAdapter tableBackgroundColor] 8 UIKitCore +0x1643a44 ___39-[UITableView _applyAppearanceDefaults]_block_invoke 9 UIKitCore +0x196f3d0 +[UIView _performSystemAppearanceModifications:] 10 UIKitCore +0x1643978 -[UITableView _applyAppearanceDefaults] 11 UIKitCore +0x202854 -[UITableView _setupTableViewCommon] 12 UIKitCore +0x1643760 -[UITableView initWithFrame:style:] 13 Application +0x30b6a40 closure #1 in variable initialization expression of MyAppClass.tableView 14 Application +0x30b6ef0 MyAppClass.init(frame:) Has anyone else seen something like this? Any insights or advice is much appreciated, thank you!
1
0
62
2d
Can I submit the app I submitted to the app store to SSC at the same time?
Hi, I recently built an app and I’m planning to publish it on the App Store. Since the Swift Student Challenge (SSC) is coming up, I’m also considering submitting the same project by converting it into a Swift Playground (with some content trimmed to meet the rules). I believe both I and the project are eligible. My question: if I publish the app on the App Store first and then submit it to SSC, could that violate the rules or lead to rejection? I also have a concern: because I’m a minor, Apple requires the App Store developer name to be my mother’s. However, the app was entirely developed by me. my mother and anyone else did not participate(My mother can't even use a computer.). I’m worried this might create confusion and make judges think I copied someone else’s work, which I did not. Would you recommend publishing on the App Store now, waiting until after SSC, or taking a different approach? Thank you.
1
0
282
2d
How to avoid this thread priority inversions ?
Context: Xcode 16.4, Appkit In a windowController, I need to create and send a mouseDown event (newMouseDownEvent). I create the event with: let newMouseDownEvent = NSEvent.mouseEvent( with: .leftMouseDown, location: clickPoint, // all other fields I also need to make window key and front, otherwise the event is not handled.   func simulateMouseDown() { self.window?.makeFirstResponder(self.window) self.calepinFullView.perform(#selector(NSResponder.self.mouseDown(with:)), with: newMouseDownEvent!) }   As I have to delay the call( 0.5 s), I use asyncAfter: DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, qos: .userInteractive) { self.simulateMouseDown() }   It works as intended, but that generates the following (purple) warning at runtime: [Internal] Thread running at User-interactive quality-of-service class waiting on a lower QoS thread running at Default quality-of-service class. Investigate ways to avoid priority inversions I have tried several solutions, change qos in await: DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, qos: ..default) call from a DispatchQueue let interactiveQueue = DispatchQueue.global(qos: .userInteractive) interactiveQueue.async { self.window?.makeFirstResponder(self.window) self.calepinFullView.perform(#selector(NSResponder.self.mouseDown(with:)), with: newMouseDownEvent!) } But that's worse, it crashes with the following error: FAULT: NSInternalInconsistencyException: -[HIRunLoopSemaphore wait:] has been invoked on a secondary thread; the problem is likely in a much shallower frame in the backtrace; { NSAssertFile = "HIRunLoop.mm"; NSAssertLine = 709; }   How to eliminate the priority inversion risk (not just silencing the warning) ?
0
0
65
3d
NavigationTitle in LiquidGlass style
Hello everyone. I want to do navigationTitle (located on the top side on MacOS system) in LiquidGlass style. now my solution look like: just black rectangle. But i want like this: opacity and LiquidGlass. Like in Photo app in MacOS. Please help me, thank you in advance. My code: struct RootView: View { @Environment(\.horizontalSizeClass) var hSize var body: some View { if hSize == .regular { DesktopLayout() .navigationTitle("title") .toolbarBackground(.ultraThinMaterial, for: .automatic) } else { MobileLayout() } } }
0
0
275
3d
Scheduled events reach threshold almost immediately on iOS 26.2
Hi, we are developing a screen time management app. The app locks the device after it was used for specified amount of time. After updating to iOS 26.2, we noticed a huge issue: the events started to fire (reach the threshold) in the DeviceActivityMonitorExtension prematurely, almost immediately after scheduling. The only solution we've found is to delete the app and reboot the device, but the effect is not lasting long and this does not always help. Before updating to iOS 26, events also used to sometimes fire prematurely, but rescheduling the event often helped. Now the rescheduling happens almost every second and the events keep reaching the threshold prematurely. Can you suggest any workarounds for this issue?
2
2
145
4d
Error in Xcode console
Lately I am getting this error. GenerativeModelsAvailability.Parameters: Initialized with invalid language code: en-GB. Expected to receive two-letter ISO 639 code. e.g. 'zh' or 'en'. Falling back to: en Does anyone know what this is and how it can be resolved. The error does not crash the app
4
1
1.5k
5d
How to do settings icon for menu in SwiftUI?
Hi everyone. Can you help me with my settings icon design. I`m trying to create circular setting button using Menu. My code here: struct MenuView: View { var body: some View { Menu { Text("Hello") Text("How are you") } label: { Image(systemName: "gearshape.fill") .clipShape(Circle()) } .clipShape(Circle()) .padding(.top, 10) .padding(.leading, 20) } } You can see my try, this one looks wrong. It should be like this: Just Circle with setting image inside. Thank you an advance 😭🙏🛐
1
0
493
5d
SwiftUI Menu label: How to center an icon inside a circle?
Hi Everyone. Can you help me with my settings icon design. I'm trying to create a circular settings button using Menu. My code here: struct MenuView: View { var body: some View { Menu { Text("Hello") Text("How are you") } label: { Image(systemName: "gearshape.fill") .clipShape(Circle()) } .clipShape(Circle()) .padding(.top, 10) .padding(.leading, 20) } } You can see my try, this one looks wrong. It should be like this: Just Circle with setting image inside. Thank you an advance 😭🙏🛐
1
0
422
5d
Content Filter Permission Prompt Not Appearing in TestFlight
I added a Content Filter to my app, and when running it in Xcode (Debug/Release), I get the expected permission prompt: "Would like to filter network content (Allow / Don't Allow)". However, when I install the app via TestFlight, this prompt doesn’t appear at all, and the feature doesn’t work. Is there a special configuration required for TestFlight? Has anyone encountered this issue before? Thanks!
20
1
819
5d
File Download Support in SwiftUI Native WebView (iOS 26+)
I am using the native SwiftUI WebView and WebPage APIs (iOS 26+) and would like to implement file download functionality using the native SwiftUI WebView. However, I have not been able to find any APIs equivalent to WKDownload. In WKWebView, the WKDownload API can be used to handle downloads. I am looking for a similar API or recommended approach in the native SwiftUI WebView that would allow downloading files. If anyone has guidance or suggestions on how to implement this, I would appreciate your help.
0
1
415
6d
Is it possible to open the Settings app programatically in watchOS?
I'm currently using Swift to write an independent Apple Watch app for watchOS 7+. My app uses Location Services, and in case the user doesn't allow that at first, I'd like to have a button inside my watchOS app to send my user to the part of the Settings app (inside watchOS) where he can give the appropriate permissions for the app. I know that in iOS/macOS you can use the openSettingsURLString string from UIApplication to do what I want, but it's not available in watchOS and I haven't found any equivalent resource inside the WKExtension class (normally the equivalent for UIApplication in the watchOS environment). Does anyone know if there's any way to programatically open the Apple Watch Settings app from my watchOS app? I'm asking since as far as I understand asking for Location permissions again would not work since the user has already refused to allow the permissions before, making the authorization status "denied". I understand as well that there's the possibility of showing a modal and directing the user to go to Settings and allow the use of location services (as in "Please go to Settings > Privacy > Location Services > [AppName] to allow the use of location services") but I'd like if I could direct the user there instead as one might do in iOS. The code below is what I'm trying to do - but (of course) it crashes since I'm not actually passing any system URL. .alert(isPresented: $alertVisible) { Alert (title: Text("Please allow our app to use location services in order to get Weather Data"), message: Text("Go to Settings?"), primaryButton: .default(Text("Settings"), action: { WKExtension.shared().openSystemURL(URL(string: "")!) //UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!) }),
1
3
1k
6d
ScreenCaptureKit recording output is corrupted when captureMicrophone is true
Hello everyone, I'm working on a screen recording app using ScreenCaptureKit and I've hit a strange issue. My app records the screen to an .mp4 file, and everything works perfectly until the .captureMicrophone is false In this case, I get a valid, playable .mp4 file. However, as soon as I try to enable the microphone by setting streamConfig.captureMicrophone = true, the recording seems to work, but the final .mp4 file is corrupted and cannot be played by QuickTime or any other player. This happens whether capturesAudio (app audio) is on or off. I've already added the "Privacy - Microphone Usage Description" (NSMicrophoneUsageDescription) to my Info.plist, so I don't think it's a permissions problem. I have my logic split into a ScreenRecorder class that manages state and a CaptureEngine that handles the SCStream. Here is how I'm configuring my SCStream: ScreenRecorder.swift // This is my main SCStreamConfiguration private var streamConfiguration: SCStreamConfiguration { var streamConfig = SCStreamConfiguration() // ... other HDR/preset config ... // These are the problem properties streamConfig.capturesAudio = isAudioCaptureEnabled streamConfig.captureMicrophone = isMicCaptureEnabled // breaks it if true streamConfig.excludesCurrentProcessAudio = false streamConfig.showsCursor = false if let region = selectedRegion, let display = currentDisplay { // My region/frame logic (works fine) let regionWidth = Int(region.frame.width) let regionHeight = Int(region.frame.height) streamConfig.width = regionWidth * scaleFactor streamConfig.height = regionHeight * scaleFactor // ... (sourceRect logic) ... } streamConfig.pixelFormat = kCVPixelFormatType_32BGRA streamConfig.colorSpaceName = CGColorSpace.sRGB streamConfig.minimumFrameInterval = CMTime(value: 1, timescale: 60) return streamConfig } And here is how I'm setting up the SCRecordingOutput that writes the file: ScreenRecorder.swift private func initRecordingOutput(for region: ScreenPickerManager.SelectedRegion) throws { let screeRecordingOutputURL = try RecordingWorkspace.createScreenRecordingVideoFile( in: workspaceURL, sessionIndex: sessionIndex ) let recordingConfiguration = SCRecordingOutputConfiguration() recordingConfiguration.outputURL = screeRecordingOutputURL recordingConfiguration.outputFileType = .mp4 recordingConfiguration.videoCodecType = .hevc let recordingOutput = SCRecordingOutput(configuration: recordingConfiguration, delegate: self) self.recordingOutput = recordingOutput } Finally, my CaptureEngine adds these to the SCStream: CaptureEngine.swift class CaptureEngine: NSObject, @unchecked Sendable { private(set) var stream: SCStream? private var streamOutput: CaptureEngineStreamOutput? // ... (dispatch queues) ... func startCapture(configuration: SCStreamConfiguration, filter: SCContentFilter, recordingOutput: SCRecordingOutput) async throws { let streamOutput = CaptureEngineStreamOutput() self.streamOutput = streamOutput do { stream = SCStream(filter: filter, configuration: configuration, delegate: streamOutput) // Add outputs for raw buffers (not used for file recording) try stream?.addStreamOutput(streamOutput, type: .screen, sampleHandlerQueue: videoSampleBufferQueue) try stream?.addStreamOutput(streamOutput, type: .audio, sampleHandlerQueue: audioSampleBufferQueue) try stream?.addStreamOutput(streamOutput, type: .microphone, sampleHandlerQueue: micSampleBufferQueue) // Add the file recording output try stream?.addRecordingOutput(recordingOutput) try await stream?.startCapture() } catch { logger.error("Failed to start capture: \(error.localizedDescription)") throw error } } // ... (stopCapture, etc.) ... } When I had the .captureMicrophone value to be false, I get a perfect .mp4 video playable everywhere, however, when its true, I am getting corrupted video which doesn't play at all :-
1
0
428
1w
Does anyone know how to achieve this custom MKAnnotation?
I’ve notice that in Maps, some pins contain images and do not have the little triangle at the bottom of it, yet they still animate the same when clicked. How could this be achieved? I believe the name of this annotation is MKMapFeatureAnnotation. I've tried this and it did not give the same result. I'm able to create a custom MKMarkerAnnotationView but it does not animate the same (balloon animation like the MKMapFeatureAnnotation). I was looking forward to create a custom MKMapFeatureAnnotation similar in design which would animate the same. Unfortunately, I cannot create a custom MKMapFeatureAnnotation because everything is privated
0
0
162
1w