Construct and manage a graphical, event-driven user interface for your macOS app using AppKit.

AppKit Documentation

Posts under AppKit subtopic

Post

Replies

Boosts

Views

Activity

Drag-and-Drop from macOS Safari to NSItemProvider fails due to URL not being a file:// URL
(Using macOS 26 Beta 9 and Xcode 26 Beta 7) I am trying to support basic onDrop from a source app to my app. I am trying to get the closest "source" representation of a drag-and-drop, e.g. a JPEG file being dropped into my app shouldn't be converted, but stored as a JPEG in Data. Otherwise, everything gets converted into TIFFs and modern iPhone photos get huge. I also try to be a good app, and provide asynchronous support. Alas, I've been running around for days now, where I can now support Drag-and-Drop from the Finder, from uncached iCloud files with Progress bar, but so far, drag and dropping from Safari eludes me. My code is as follows for the onDrop support: Image(nsImage: data.image).onDrop(of: Self.supportedDropItemUTIs, delegate: self) The UTIs are as follows: public static let supportedDropItemUTIs: [UTType] = [ .image, .heif, .rawImage, .png, .tiff, .svg, .heic, .jpegxl, .bmp, .gif, .jpeg, .webP, ] Finally, the code is as follows: public func performDrop(info: DropInfo) -> Bool { let itemProviders = info.itemProviders(for: Self.supportedDropItemUTIs) guard let itemProvider = itemProviders.first else { return false } let registeredContentTypes = itemProvider.registeredContentTypes guard let contentType = registeredContentTypes.first else { return false } var suggestedName = itemProvider.suggestedName if suggestedName == nil { switch contentType { case UTType.bmp: suggestedName = "image.bmp" case UTType.gif: suggestedName = "image.gif" case UTType.heic: suggestedName = "image.heic" case UTType.jpeg: suggestedName = "image.jpeg" case UTType.jpegxl: suggestedName = "image.jxl" case UTType.png: suggestedName = "image.png" case UTType.rawImage: suggestedName = "image.raw" case UTType.svg: suggestedName = "image.svg" case UTType.tiff: suggestedName = "image.tiff" case UTType.webP: suggestedName = "image.webp" default: break } } let progress = itemProvider.loadInPlaceFileRepresentation(forTypeIdentifier: contentType.identifier) { url, _, error in if let error { print("Failed to get URL from dropped file: \(error)") return } guard let url else { print("Failed to get URL from dropped file!") return } let queue = OperationQueue() queue.underlyingQueue = .global(qos: .utility) let intent = NSFileAccessIntent.readingIntent(with: url, options: .withoutChanges) let coordinator = NSFileCoordinator() coordinator.coordinate(with: [intent], queue: queue) { error in if let error { print("Failed to coordinate data from dropped file: \(error)") return } do { // Load file contents into Data object let data = try Data(contentsOf: intent.url) Dispatch.DispatchQueue.main.async { self.data.data = data self.data.fileName = suggestedName } } catch { print("Failed to load coordinated data from dropped file: \(error)") } } } DispatchQueue.main.async { self.progress = progress } return true } For your information, this code is at the state where I gave up and sent it here, because I cannot find a solution to my issue. Now, this code works everywhere, except for dragging and dropping from Safari. Let's pretend I go to this web site: https://commons.wikimedia.org/wiki/File:Tulip_Tulipa_clusiana_%27Lady_Jane%27_Rock_Ledge_Flower_Edit_2000px.jpg and I try to drag-and-drop the image, it will fail with the following error: URL https://upload.wikimedia.org/wikipedia/commons/c/cf/Tulip_Tulipa_clusiana_%27Lady_Jane%27_Rock_Ledge_Flower_Edit_2000px.jpg is not a file:// URL. And then, fail with the dreaded Failed to get URL from dropped file: Error Domain=NSItemProviderErrorDomain Code=-1000 As far as I can tell, the problem lies in the opaque NSItemProvider receiving a web site URL from Safari. I tried most solutions, I couldn't retrieve that URL. The error happens in the callback of loadInPlaceFileRepresentation, but also fails in loadFileRepresentation. I tried hard-requesting a loadObject of type URL, but there's only one representation for the JPEG file. I tried only putting .url in the requests, but it would not transfer it. Anyone solved this mystery?
5
0
121
13h
Resizing text to fit available space
My app displays some text that should appear the same regardless of the container view or window size, i.e. it should grow and shrink with the container view or window. On iOS there is UILabel.adjustsFontSizeToFitWidth but I couldn't find any equivalent API on macOS. On the internet some people suggest to iteratively set a smaller font size until the text fits the available space, but I thought there must be a more efficient solution. How does UILabel.adjustsFontSizeToFitWidth do it? My expectation was that setting a font's size to a fraction of the window width or height would do the trick, but when resizing the window I can see a slightly different portion of it. class ViewController: NSViewController { override func loadView() { view = MyView(frame: CGRect(x: 0, y: 0, width: 400, height: 400)) NSLayoutConstraint.activate([view.widthAnchor.constraint(equalTo: view.heightAnchor, multiplier: 3), view.heightAnchor.constraint(greaterThanOrEqualToConstant: 100)]) } } class MyView: NSView { let textField = NSTextField(labelWithString: String(repeating: "a b c d e f g h i j k l m n o p q r s t u v w x y z ", count: 2)) override init(frame frameRect: NSRect) { super.init(frame: frameRect) textField.translatesAutoresizingMaskIntoConstraints = false textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) addSubview(textField) NSLayoutConstraint.activate([textField.topAnchor.constraint(equalTo: topAnchor), textField.leadingAnchor.constraint(equalTo: leadingAnchor), textField.trailingAnchor.constraint(equalTo: trailingAnchor)]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func resize(withOldSuperviewSize oldSize: NSSize) { // textField.font = .systemFont(ofSize: frame.width * 0.05) textField.font = .systemFont(ofSize: frame.height * 0.1) } }
Topic: UI Frameworks SubTopic: AppKit Tags:
7
0
100
2d
NSMutableAttributedString and NSTextTable
I'm using NSTextTable to format panels of stand-out text within body text. Paragraphs within the panel are handled as individual NSTextTableBlocks within the table. Each block is added to the NSMutableParagraphStyle that is part of the attributed string within the block's attributes. That's all fine and it works. But... Occasionally I see undrawn lines within the panel. These disappear (or sometimes appear) when the parent window (and thus the NSTextView holding the rendered attributed string) is resized. Lines do not always appear, and when they do they are not always in the same place. The height of the gap varies. I see this behaviour with these panels and with tables. What's common to both cases is not only the use of NSTextTable and NSTextTableBlock etc., but crucially (I think) the use of block margins. If I disable margins (which looks OK for the panels, but isn't right for tables), the problem disappears. So, a bug or (more likely) I'm missing a key part of view rendering or margin set up. But what? Code here: https://github.com/smittytone/PreviewMarkdown/blob/930f5f32aa0b3b77ec3f4f53436a79e10bb26f18/Markdown%20Previewer/Styler.swift#L882 Running 14.6.1 on an M3. I'm using TextKit 1 because I'm using an NSLayoutManager subclass to override certain text underlines (not used in panels as outlined above, or tables).
Topic: UI Frameworks SubTopic: AppKit
3
0
355
3d
How to Handle App Focus When Launching Another App During Secure Event Input
Hi everyone, I'm encountering a behaviour related to Secure Event Input on macOS and wanted to understand if it's expected or if there's a recommended approach to handle it. Scenario: App A enables secure input using EnableSecureEventInput(). While secure input is active, App A launches App B using NSWorkspace or similar. App B launches successfully, but it does not receive foreground focus — it starts in the background. The system retains focus on App A, seemingly to preserve the secure input session. Observed Behavior: From what I understand, macOS prevents app switching during Secure Event Input to avoid accidental or malicious focus stealing (e.g., to prevent UI spoofing during password entry). So: Input focus remains locked to App A. App B runs but cannot become frontmost unless the secure input session ends or App B is brought to the frontmost by manual intervention or by running a terminal script. This is consistent with system security behaviour, but it presents a challenge when App A needs to launch and hand off control to another app. Questions: Is this behaviour officially documented anywhere? Is there a recommended pattern for safely transferring focus to another app while Secure Event Input is active? Would calling DisableSecureEventInput() just before launching App B be the appropriate (and safe) solution? Or is there a better way to defer the transition? Thanks in advance for any clarification or advice.
0
0
25
6d
Bug or Feature: Changes to Window Reopen Behavior in macOS 26
Since macOS 26 Beta 1, I notice that the window reopening behavior had changed. Say there are two desktops (spaces), one might: open an app window in desktop 1 close that window switch to desktop 2 reopen the app window (by click on dock tile, spotlight search...) Prior to macOS 26, that window will always reopen in current desktop. This is IMO the right behavior because these windows are most likely transient (message app, chat app, utilities app or note app). In macOS 26, however, will switch to desktop 1 (where the window is closed) and reopen the window in desktop 1. This is weird to me because: Window is "closed", hence it should not be attached to desktop 1 anymore, unlike minimize. Switching desktop interrupts user's current workflow. It's annoying to switch back specially when there're many desktops. This behavior is inconsistent. Some reopen in current desktop, some reopen in previous desktop. Apps like Music, Notes and Calendar reopened in previous desktop, while Mail, Messages, and Freeform reopened in current desktop. I did a little bit of experiment, and find out that apps that reopened in current desktop are most likely because they take an extra step to release the window when it's closed. I believe this is a bug, so I fire a feedback (FB18016497) back in beta 1. But I did not get any response or similar report from others, to a point that I kinda wonder if this is intended. I can easily force my app to reopen in current desktop by nullifying my window controller in windowWillClose, but this behavior essentially change how one can use the Spaces feature that I think I should bring this up to the community and see what other developers or engineers thinks about it.
Topic: UI Frameworks SubTopic: AppKit Tags:
2
0
113
6d
NSScrollPocket overlay appearing on scroll views in NSSplitViewController on macOS Tahoe
I have an NSSplitViewController with three columns: sidebar full-height content view with NSScrollView/NSTableView detail view. There's no (visible) titlebar and no toolbar. This layout has worked fine for years, but in Tahoe an unwanted overlay (~30-50px high) appears at the top of any column containing a scroll view with table content. Xcode suggests it's an NSScrollPocket. My research suggests it... Only affects columns with NSScrollView Plain NSView columns are unaffected Overlay height varies (~50px or ~30px depending on how I mess with title / toolbar settings) Disabling titlebar/toolbar settings reduces but doesn't eliminate the overlay The overlay obscures content and there doesn't appear to be any API to control its visibility. Is this intended behavior, and if so, is there a way to disable it for applications that don't need this UI element? If it helps visualise the desired result, the app is https://indigostack.app Any guidance would be appreciated!
Topic: UI Frameworks SubTopic: AppKit
2
1
108
1w
Printing of NSTextView
I have a document-based macOS app written in Objective-C, and each document window contains a scrollable NSTextView. I know that printing can get complicated if you want to do nice pagination, but is there a quick and dirty way to get basic printing working? As it is, the print panel shows up, but its preview area is totally blank. Here's the current printing part of my NSDocument subclass. - (NSPrintInfo *)printInfo { NSPrintInfo *printInfo = [super printInfo]; [printInfo setHorizontalPagination: NSPrintingPaginationModeFit]; [printInfo setHorizontallyCentered: NO]; [printInfo setVerticallyCentered: NO]; [printInfo setLeftMargin: 72.0]; [printInfo setRightMargin: 72.0]; [printInfo setTopMargin: 72.0]; [printInfo setBottomMargin: 72.0]; return printInfo; } - (void)printDocumentWithSettings:(NSDictionary<NSPrintInfoAttributeKey, id> *)printSettings showPrintPanel:(BOOL)showPrintPanel delegate:(id)delegate didPrintSelector:(SEL)didPrintSelector contextInfo:(void *)contextInfo { NSPrintInfo* thePrintInfo = [self printInfo]; [thePrintInfo setVerticallyCentered: NO ]; NSPrintOperation *op = [NSPrintOperation printOperationWithView: _textView printInfo: thePrintInfo ]; [op runOperationModalForWindow: _docWindow delegate: delegate didRunSelector: didPrintSelector contextInfo: contextInfo]; }
Topic: UI Frameworks SubTopic: AppKit Tags:
2
0
116
1w
Unity PolySpatia
We are encountering an issue with noticeable lag when interacting with objects in Unity using the XR Interaction Toolkit. Even with the Movement Type set to Instantaneous, interactable objects still show a delay when following hand movements, especially at higher speeds. Is there additional configuration required, or any recommended steps to eliminate this latency? https://wifi4compressed.com/
Topic: UI Frameworks SubTopic: AppKit
0
0
13
1w
NSProgressIndicator indeterminate bar does not work in Tahoe Beta 8
We have an app that uses a NSProgressIndicator indeterminate and it no longer animates on Tahoe (currently beta 8). I did a empty swift app using storyboards and added this to the view controller: override func viewDidLoad() { super.viewDidLoad() let progressIndicator=NSProgressIndicator.init(frame: NSMakeRect(0, 300, 400,20)) progressIndicator.style = .bar progressIndicator.isIndeterminate = true progressIndicator.isDisplayedWhenStopped=true self.view.addSubview(progressIndicator) progressIndicator.startAnimation(self) } Works fine in macOS 15, no animation in macOS 26. If I switch to the style to spinner, it animates fine. Filed feedback FB19933934
Topic: UI Frameworks SubTopic: AppKit
0
0
143
1w
Why is the nib still loaded even though the class has been registered with NSCollectionView?
I implemented a subclass of NSCollectionViewItem: class ViewItem: NSCollectionViewItem { override func loadView() { self.view = NSView() } } and registed to NSCollectionView: class PictureFrameThemeListView: NSCollectionView { init(viewModel: PictureFrameViewModel) { super.init(frame: .zero) self.register(ViewItem.self, forItemWithIdentifier: .item) } However, when calling makeItem(withIdentifier:for:), the following error is prompted: FAULT: NSInternalInconsistencyException: -[NSNib _initWithNibNamed:bundle:options:] could not load the nib 'Item' in bundle NSBundle What confuses me is that I registered the subclass of NSCollectionViewItem, why do NSCollectionView to init the NSNib?
Topic: UI Frameworks SubTopic: AppKit Tags:
2
0
27
1w
Equivalent of coalescedTouchesForTouch in AppKit?
This method on UIEvent gets you more touch positions, and I think it's useful for a drawing app, to respond with greater precision to the position of the Pencil stylus. Is there a similar thing in macOS, for mouse or tablet events? I found this property mouseCoalescingEnabled, but the docs there don't describe how to get the extra events.
Topic: UI Frameworks SubTopic: AppKit Tags:
1
0
142
1w
Compatibility Issues with Main Event Loop in macOS 26 Beta
I have a standard Mac project created using Xcode templates with Storyboard. I manually removed the window from the Storyboard file and use ViewController.h as the base class for other ViewControllers. I create new windows and ViewControllers programmatically, implementing the UI entirely through code. However, I've discovered that on all macOS versions prior to macOS 26 beta, the application would trigger automatic termination due to App Nap under certain circumstances. The specific steps are: Close the application window (the application doesn't exit immediately at this point) Click on other windows or the desktop, causing the application to lose focus (though this description might not be entirely accurate - the app might have already lost focus when the window closed, but the top menu bar still shows the current application immediately after window closure) The application automatically terminates In previous versions, I worked around this issue by manually executing [[NSApplication sharedApplication] run]; to create an additional main event loop, keeping the application active (although I understand this isn't an ideal approach). However, in macOS 26 beta, I've found that calling [[NSApplication sharedApplication] run]; causes all NSButton controls I created in the window to become unresponsive to click events, though they still respond to mouse enter events. Through recent research, I've learned that the best practice for preventing App Nap automatic termination is to use [[NSProcessInfo processInfo] disableAutomaticTermination:@"User interaction required"]; to increment the automatic termination reference count. My questions are: Why did calling [[NSApplication sharedApplication] run]; work properly on macOS versions prior to 15.6.1? Why does calling [[NSApplication sharedApplication] run]; in macOS 26 beta cause buttons to become unresponsive to click events?
0
1
80
1w
Avoiding a macOS Tahoe window corner in objective-c
I watched the video Build an AppKit app with the new design and followed the discussion about how to have a button avoid a window corner. However, the code is in Swift and my codebase is still heavily written in objective-c. I've searched NSView.h but can't find anything new related to safe areas and corners. How are we supposed to avoid corners using objective-c?
Topic: UI Frameworks SubTopic: AppKit
3
0
133
2w
NSTableView.reloadData(forRowIndexes:columnIndexes:) causes wrong subview layout when usesAutomaticRowHeights = true
I have a table view where each row has two labels, one left-aligned and one right-aligned. I would like to reload a single row, but doing so causes the right-aligned label to hug the left-aligned label. Before the reload: After the reload: Reloading the whole table view instead, or disabling automatic row height, solves the issue. Can a single row be reloaded without resorting to these two workarounds? I created FB13534100 1.5 years ago but got no response. class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate { override func loadView() { let tableView = NSTableView() tableView.translatesAutoresizingMaskIntoConstraints = false tableView.dataSource = self tableView.delegate = self tableView.usesAutomaticRowHeights = true let column = NSTableColumn() column.width = 400 tableView.addTableColumn(column) let scrollView = NSScrollView(frame: CGRect(x: 0, y: 0, width: 500, height: 500)) scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.documentView = tableView view = scrollView Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { _ in print("reload") tableView.reloadData(forRowIndexes: IndexSet(integer: 2), columnIndexes: IndexSet(integer: 0)) // tableView.reloadData() } } func numberOfRows(in tableView: NSTableView) -> Int { return 5 } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let cell = NSTableCellView() let textField1 = NSTextField(labelWithString: "hello") textField1.translatesAutoresizingMaskIntoConstraints = false let textField2 = NSTextField(wrappingLabelWithString: "world") textField2.translatesAutoresizingMaskIntoConstraints = false textField2.alignment = .right let stack = NSStackView(views: [ textField1, textField2 ]) stack.translatesAutoresizingMaskIntoConstraints = false stack.distribution = .fill cell.addSubview(stack) NSLayoutConstraint.activate([stack.topAnchor.constraint(equalTo: cell.topAnchor, constant: 0), stack.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 0), stack.bottomAnchor.constraint(equalTo: cell.bottomAnchor, constant: 0), stack.trailingAnchor.constraint(equalTo: cell.trailingAnchor, constant: 0)]) return cell } }
Topic: UI Frameworks SubTopic: AppKit Tags:
2
0
87
2w
NSStatusIcon mysteriously vanishes from menu bar
I have an app who's entire UI is a menu attached to a NSStatusIcon and after doing things in my app that largely work well, sometimes the icon is mysteriously vanishing from menu bar, its menu inaccessible. I've seen it happen when launching normally, freshly built debug builds or release build installed from TestFlight, also launched from Xcode attached to lldb. In the latter case I can poke around in the state of the app but haven't been able to find any answers yet. Things of note: The menu bar icon isn't being removed in any normal fashion, it leaves an unnatural gap in the menu bar when my icon should be. My app isn't crashing, hanging, or getting terminated: as evidenced by seeing it still running within Xcode. A part of my app that runs off a recurring timer responds normally to breakpoints. The NSStatusIcon isn't getting released, its isVisible flag remains true, its button isn't going anywhere and neither is its button image. Nothing interesting is logged to the Xcode console, I haven't found anything interesting in Console.app. Does anyone know the state an app could get into that has this effect on its NSStatusIcon?
Topic: UI Frameworks SubTopic: AppKit
0
0
110
3w
NSDocument doesn't autosave last changes
I had noticed an unsettling behaviour about NSDocument some years ago and created FB7392851, but the feedback didn't go forward, so I just updated it and hopefully here or there someone can explain what's going on. When running a simple document-based app with a text view, what I type before closing the app may be discarded without notice. To reproduce it, you can use the code below, then: Type "asdf" in the text view. Wait until the Xcode console logs "saving". You can trigger it by switching to another app and back again. Type something else in the text view, such as "asdf" on a new line. Quit the app. Relaunch the app. The second line has been discarded. Am I doing something wrong or is this a bug? Is there a workaround? class ViewController: NSViewController { @IBOutlet var textView: NSTextView! } class Document: NSDocument { private(set) var text = "" override class var autosavesInPlace: Bool { return true } override func makeWindowControllers() { let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil) let windowController = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("Document Window Controller")) as! NSWindowController (windowController.contentViewController as? ViewController)?.textView.string = text self.addWindowController(windowController) } override func data(ofType typeName: String) throws -> Data { Swift.print("saving") text = (windowControllers.first?.contentViewController as? ViewController)?.textView.string ?? "" return Data(text.utf8) } override func read(from data: Data, ofType typeName: String) throws { text = String(decoding: data, as: UTF8.self) (windowControllers.first?.contentViewController as? ViewController)?.textView.string = text } }
Topic: UI Frameworks SubTopic: AppKit Tags:
4
0
72
3w
Crash when assigning NSImage to `@objc dynamic var` property
Xcode downloaded a crash report for my app which I don't quite understand. It seems the following line caused the crash: myEntity.image = newImage where myEntity is of type MyEntity: class MyEntity: NSObject, Identifiable { @objc dynamic var image: NSImage! ... } The code is called on the main thread. According to the crash report, thread 0 makes that assignment, and at the same time thread 16 is calling [NSImageView asynchronousPreparation:prepareResultUsingParameters:]. What could cause such a crash? Could I be doing something wrong or is this a bug in macOS? crash.crash
11
0
136
3w
NSTextView.shouldDrawInsertionPoint doesn't work with TextKit 2
The following code only ever causes shouldDrawInsertionPoint to be printed (no drawInsertionPoint), but even if that method returns false, the blinking insertion point is still drawn. On the other hand, with TextKit 1 it works as expected. Is there a way to hide the default insertion point in TextKit 2? My app draws its own. I've filed FB13684251. class TextView: NSTextView { override var shouldDrawInsertionPoint: Bool { print("shouldDrawInsertionPoint") return false } override func drawInsertionPoint(in rect: NSRect, color: NSColor, turnedOn flag: Bool) { print("drawInsertionPoint", flag) } } ``
Topic: UI Frameworks SubTopic: AppKit Tags:
9
0
107
3w
macOS 26: NSTokenField crashes due to NSGenericException caused by too many Update Constraints
This example application crashes when entering any text to the token field with FAULT: NSGenericException: The window has been marked as needing another Update Constraints in Window pass, but it has already had more Update Constraints in Window passes than there are views in the window. The app uses controlTextDidChange to update a live preview where it accesses the objectValue of the token field. If one character is entered, it also looks like the NSTokenFieldDelegate methods tokenField(_:styleForRepresentedObject:) tokenField(_:editingStringForRepresentedObject:) tokenField(_:representedObjectForEditing:) are called more than 10000 times until the example app crashes on macOS Tahoe 26 beta 6. I've reported this issue with beta 1 as FB18088608, but haven't heard back so far. I have multiple occurrences of this issue in my app, which is working fine on previous versions of macOS. I haven't found a workaround yet, and I’m getting anxious of this issue persisting into the official release.
0
0
49
3w