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"
Swift
RSS for tagSwift is a powerful and intuitive programming language for Apple platforms and beyond.
Posts under Swift tag
200 Posts
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
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.
Topic:
Community
SubTopic:
Swift Student Challenge
Tags:
Swift Student Challenge
App Store
Swift
Swift Playground
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) ?
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 ?
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()
}
}
}
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));
}];
});
}
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?
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
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 😭🙏🛐
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 😭🙏🛐
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!
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.
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)!)
}),
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 :-
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
When using UITraitBridgedEnvironmentKey to pass a trait value to the swift environment, it causes a crash when trying to access the value from the environment.
The issue seems to be related to how swift uses the UITraitBridgedEnvironmentKey protocol since the crash occurs in swift::_getWitnessTable () from lazy protocol witness table accessor…. It can occur when calling any function that is generic using the UITraitBridgedEnvironmentKey type.
I originally encountered the issue when trying to use a UITraitBridgedEnvironmentKey in SwiftUI, but have been able to reproduce the issue with any function with a similar signature.
https://developer.apple.com/documentation/swiftui/environmentvalues/subscript(_:)-9zku
Steps to Reproduce
Requirements for the issue to occur
Project with a minimum iOS version of iOS 16
Build the project with Xcode 26
Run on iOS 18
Add the following code to a project and call foo(key: MyCustomTraitKey.self) from anywhere.
@available(iOS 17.0, *)
func foo<K>(key: K.Type) where K: UITraitBridgedEnvironmentKey {
// Crashes before this is called
}
@available(iOS 17.0, *)
public enum MyCustomTraitKey: UITraitBridgedEnvironmentKey {
public static let defaultValue: Bool = false
public static func read(from traitCollection: UITraitCollection) -> Bool { false }
public static func write(to mutableTraits: inout UIMutableTraits, value: Bool) {}
}
// The crash will occur when calling this. It can be added to a project anywhere
// The sample project calls it from scene(_:willConnectTo:options:)
foo(key: MyCustomTraitKey.self)
For example, I added it to the SceneDelegate in a UIKit Project
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if #available(iOS 17, *) {
// The following line of code can be placed anywhere in a project, `SceneDelegate` is just a convenient place to put it to reproduce the issue.
foo(key: MyCustomTraitKey.self)
// ^ CRASH: Thread 1: EXC_BAD_ACCESS (code=1, address=0x10)
}
}
}
Actual Behaviour
The app crashes with the stack trace showing the place calling foo but before foo is actually called. (ie, a breakpoint or print in foo is never hit)
#0 0x000000019595fbc4 in swift::_getWitnessTable ()
#1 0x0000000104954128 in lazy protocol witness table accessor for type MyCustomTraitKey and conformance MyCustomTraitKey ()
#2 0x0000000104953bc4 in SceneDelegate.scene(_:willConnectTo:options:) at .../SceneDelegate.swift:20
The app does not crash when run on iOS 17, or 26 or when the minimum ios version is raised to iOS 17 or higher.
It also doesn't crash on iOS 16 since it's not calling foo since UITraitBridgedEnvironmentKey was added in iOS 17.
Expected behaviour
The app should not crash. It should call foo on iOS 17, 18, and 26.
Description
I've encountered a consistent hang/freeze issue in SwiftUI applications when using nested LazyVStack containers with Accessibility Inspector (simulator) or VoiceOver (physical device) enabled. The application becomes completely unresponsive and must be force-quit.
Importantly, this hang occurs in a minimal SwiftUI project with no third-party dependencies, suggesting this is a framework-level issue with the interaction between SwiftUI's lazy view lifecycle and the accessibility system.
Reproduction Steps
I've created a minimal reproduction project available here:
https://github.com/pendo-io/SwiftUI_Hang_Reproduction
To Reproduce:
Create a SwiftUI view with the following nested LazyVStack structure:
struct NestedLazyVStackView: View {
@State private var outerSections: [Int] = []
@State private var innerRows: [Int: [Int]] = [:]
var body: some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: 24) {
ForEach(outerSections, id: \.self) { section in
VStack(alignment: .leading, spacing: 8) {
Text("Section #\(section)")
// Nested LazyVStack
LazyVStack(alignment: .leading, spacing: 2) {
ForEach(innerRows[section] ?? [], id: \.self) { row in
Text("Section #\(section) - Row #\(row)")
.onAppear {
// Load more data when row appears
loadMoreInner(section: section)
}
}
}
}
.onAppear {
// Load more sections when section appears
loadMoreOuter()
}
}
}
}
}
}
Enable Accessibility Inspector in iOS Simulator:
Xcode → Open Developer Tool → Accessibility Inspector
Select your running simulator
Enable Inspection mode (eye icon)
Navigate to the view and start scrolling
Result: The application hangs and becomes unresponsive within a few seconds of scrolling
Expected Behavior
The application should remain responsive when Accessibility Inspector or VoiceOver is enabled, allowing users to scroll through nested lazy containers without freezing.
Actual Behavior
The application freezes/hangs completely
CPU usage may spike
The app must be force-quit to recover
The hang occurs consistently and is reproducible
Workaround 1: Replace inner LazyVStack with VStack
LazyVStack {
ForEach(...) { section in
VStack { // ← Changed from LazyVStack
ForEach(...) { row in
...
}
}
}
}
Workaround 2: Embed in TabView
TabView {
NavigationStack {
NestedLazyVStackView() // ← Same nested structure, but no hang
}
.tabItem { ... }
}
Interestingly, wrapping the entire navigation stack in a TabView prevents the hang entirely, even with the nested LazyVStack structure intact.
Questions for Apple
Is there a known issue with nested LazyVStack containers and accessibility traversal?
Why does wrapping the view in a TabView prevent the hang?
Are there recommended patterns for using nested lazy containers with accessibility support?
Is this a timing issue, a deadlock, or an infinite loop in the accessibility system?
Why that happens?
Reproduction Project
A complete, minimal reproduction project is available at:
https://github.com/pendo-io/SwiftUI_Hang_Reproduction
I have the following code that renders a one-page PDF:
func render() -> URL {
let renderer = ImageRenderer(content: pdfView())
let url = URL.documentsDirectory.appending(path: "filename.pdf")
renderer.render { size, context in
var document = CGRect(x: 0, y: 0, width: 2550, height: 3300)
guard let pdf = CGContext(url as CFURL, mediaBox: &document, nil) else {
return
}
pdf.beginPDFPage(nil)
context(pdf)
pdf.endPDFPage()
pdf.closePDF()
}
return url
}
func pdfView() -> some View {
Text("View")
}
How can this be modified so that it renders a PDF with more than one page?
I tried making a concurrency-safe data queue. It was going well, until memory check tests crashed.
It's part of an unadvertised git project. Its location is:
https://github.com/CTMacUser/SynchronizedQueue/commit/84a476e8f719506cbd4cc6ef513313e4e489cae3
It's the blocked-off method "`memorySafetyReferenceTypes'" in "SynchronizedQueueTests.swift."
Note that the file and its tests were originally AI slop.
In WKWebView, there is the WKUIDelegate method:
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {}
This delegate method provides a callback when a new window (for example, target="_blank") is requested in the web view.
However, in native SwiftUI (iOS 26), WebView / WebPage APIs do not provide an equivalent delegate method to handle new window requests.
As a workaround, I am using the following method:
public func decidePolicy(for action: WebPage.NavigationAction, preferences: inout WebPage.NavigationPreferences) async -> WKNavigationActionPolicy {}
In this method, when action.target == nil, I treat it as a new window request.
My question:
Is relying on action.target == nil in decidePolicy a reliable and future-safe way to detect new window requests in SwiftUI’s WebView, or is there a better or more recommended approach for handling target="_blank" / new window navigation in the SwiftUI WebView APIs?
Code:
public func decidePolicy(for action: WebPage.NavigationAction, preferences: inout WebPage.NavigationPreferences) async -> WKNavigationActionPolicy {
guard let webPage = webPage else { return .cancel }
// Handle case where target frame is nil (e.g., target="_blank" or window.open)
// This indicates a new window request
if action.target == nil {
print("Target frame is nil - new window requested")
// WORKAROUND: Until iOS 26 WebPage UI protocol is available, we handle new windows here
// Try to create a new WebPage through UI plugins
if handleCreateWebPage(for: webPage, navigationAction: action) != nil {
// Note: The new WebPage has been created and published to the view
return .allow
}
}
return .allow
}
I have an NSWindowController with several IBOutlets created in storyboard.
I want to add an NSView and fill it with some color. I need to place it at a specific position in views hierarchy.
I have tried 2 ways, no one succeeds.
First.
include a custom view in storyboard
connect to an IBOutlet
in an init of controller, set the layer for the view
Result: crash
Second
build programmatically
Result: I do not find where to put this code in the controller code
That's basic Cocoa, but way more painful than iOS.