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

AppKit Documentation

Post

Replies

Boosts

Views

Activity

NSError localizedDescription in another language
Even if the operating system language has been set to something else (such as Finnish), NSError.localizedDescription seems to always have the description in English. I need the error message provided by the system in Finnish, but I have no idea how to achieve this.Somebody on the internets says that in order to achieve this, one has to create a new localization in the Xcode project (which happens on the Info pane of the project settings). I don't need localizations per se, because this project is supposed to be in one single language. Either way, when I try to add a new localization (by clicking on the + button and selecting "Finnish") nothing happens. It shows an empty list of files to localize, and when I click the Finish button, nothing at all happens. No new localization is added to the list.(I'm wondering if this happens because the project has been created in an unconventional manner. More precisely, it has been created by SpriteBuilder. Changing the project to something else is pretty much out of the question, so that's not a solution.)I just want the Finnish version of localizedDescription. How can I retrieve it from the system?
5
0
3k
Sep ’15
AXIsProcessTrustedWithOptions not prompting for permission
I'm trying to use the Accessibility API and have this code: NSDictionary *options = @{(__bridge id) kAXTrustedCheckOptionPrompt : @YES}; BOOL accessibilityEnabled = AXIsProcessTrustedWithOptions((__bridge CFDictionaryRef) options);This always returns no, however it does not prompt the user for permission nor does it display the app's name in System Preferences > Security & Privacy. What do I need to test this? I could try and add the debug version manually into System Preferences but how do I know that this will work properly when released to the public? Is there any way to test this out? I am not seeing any prompt at all.
6
0
5.3k
Oct ’15
File Provider Extension, importDocumentAtURL:: can't read file at given URL (iOS 11.4.1)
I'm having troubles with Paste opertaions into my containers in File Provider extension.If I paste copied image or text into Files app -> My App -> any folder the file at fileURL can not be read (as a result can't be uploaded to my servers nor stored locally).- (void)importDocumentAtURL:(NSURL *)fileURL toParentItemIdentifier:(NSFileProviderItemIdentifier)parentItemIdentifier completionHandler:(void (^)(NSFileProviderItem _Nullable importedDocumentItem, NSError * _Nullable error))completion { NSError *readError = nil; NSData *fileData = [NSData dataWithContentsOfURL:fileURL options:NSDataReadingMappedAlways error:&readError]; NSString *readErrorMessage = readError.localizedDescription; NSURL *myFileURL = [NSFileProviderManager.defaultManager.documentStorageURL URLByAppendingPathComponent:@"temp.dat"]; NSError *copyError = nil; BOOL copyResult = [_fileManager copyItemAtURL:fileURL toURL:myFileURL error:&copyError]; NSString *copyErrorMessage = copyError.localizedDescription; ...copyResult is false, both readErrorMessage and copyErrorMessage are:The file “text.txt” couldn’t be opened because you don’t have permission to view it.What am I doing wrong here?This happens to any file copied from my container, iCloud container, as well as synthetic files produced from text/image/other data from system Clipboard.For emalple, fileURL for image.png file I'm trying to duplicate from my own container isfile:///private/var/mobile/Containers/Data/Application/80480715-574A-4E99-B588-FBDCC7F1FDFC/tmp/DDBD7C7B-56C0-4F61-94A9-109613C78F75/image.png/The same time the item being duplicated is located at:file:///private/var/mobile/Containers/Shared/AppGroup/A8C1416D-8435-407E-82B3-CE10A8439630/File%20Provider%20Storage/Document93838429/image.pngI guess I cant ready anything in /private/var/mobile/Containers/Data/Application/80480715-574A-4E99-B588-FBDCC7F1FDFC/Thanks.
12
2
46k
Sep ’18
fileImporter download progress from files in iCloud Drive
I'm using fileImporter for a Mac app. If I open a file from iCloud Drive that isn't already downloaded, I need to start the download before I can read the contents of the file. I found that I can download the file by using NSFileCoordinator or FileManager.default.startDownloadingUbiquitousItem. These APIs will begin the download, but I have no updates on the progress or if the file has been downloaded. I've tried to use NSMetadataQuery with no luck. Is there a way, either with fileImporter in SwiftUI or an AppKit API that I can receive updates for when a remote file has been downloaded, or do I need to prompt the users to download the file themselves before importing into my app?
1
1
1.2k
Sep ’21
Can NSTextView work with custom NSTextContentManager implementation? (TextKit2)
I'm trying to implement custom NSTextContentManager and use it with NSTextView, however it seems that NSTextView expect NSTextContentStorage all the time. final class MyTextContentManager: NSTextContentManager { // ... } It's added to layout manager, and NSTextView instance finds it properly: let textContentManager = MyTextContentManager() textContentManager.addTextLayoutManager(textLayoutManager) however, when I use it, I see errors at: [MyTextContentManager textStorage]: unrecognized selector sent to instance 0x600003d84870 the textStorage property is part of NSTextStorageObserving, that is not NSTextContentManager interface. It looks like NSTextView is not ready to work with custom NSTextContentManager. What did I miss?
3
0
1.8k
Sep ’21
Badge label not appearing in Monterey 12.0.1
Using the Lazarus IDE and Free Pascal the following code works in previous macOS versions, but not in Monterey: procedure TForm1.FormActivate(Sender: TObject); begin NSApp := NSApplication.sharedApplication; end; procedure TForm1.Button1Click(Sender: TObject); begin NSApp.dockTile.setBadgeLabel(NSStr('1')); end; Any ideas why it fails in Monterey? There are no related errors in the system console log.
3
0
817
Dec ’21
Popover from NSToolbarItem in Mac Catalyst app
Hi, Inside a Mac Catalyst app, I need to display a popover starting from an NSToolbarItem contained inside the app toolbar (like the Apple Maps Mac app does, see below image). In order to do that, when I press the button I need to find the toolbar item view and use it as popover anchor. How can I find the view or frame of an NSToolbarItem on Mac Catalyst? A property that could help me is the NSToolbarItem "view" property (NSView), but that property has been marked has unavailable in Mac Catalyst. Any idea? Thank you
3
3
1.2k
Feb ’22
Global accent color not respected
I am facing an odd problem with the global accent color in a macOS application targeting macOS 11 +. The color is defined in an asset catalog and its name is set as the value of the key Global Accent Color Name in the project's build settings. Despite this, the custom accent color is not applied uniformly throughout the application when the system accent color is set to multicolor. Anywhere where NSColor.controlAccentColor is used explicitly either in code or interface builder, the color is correct. However, wherever the use of the accent color (or its variants) is implicit, the blue system accent color is used instead. This includes the selection in NSMenus, the selected state of NSSegmentedControls, the selection NSOutlineView using the source list style, NSSwitch, NSPopUpButton, NSButton, etc. This problem occurs in both light and dark modes, on macOS 11 and macOS 12. I have compiled the application with Xcode 12.5, and multiple versions Xcode 13. I have found that modifying the system accent color to something other than multicolor and then back to multicolor fixes the problem, but only until the application is quit. At the next launch, the problem reappears.  I have tried all sorts of changes such as: Setting the value directly in info.plist Adding the value in an xconfig file: with the key ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME Forcing views to redraw Renaming the color in the asset catalog Creating a minimal application in an attempt to reproduce the problem. The closest I have come to a solution is investigating in detail the effective appearance of the application, from the property NSApplication.sharedApplication.effectiveAppearance.  The object returned is of the class NSCompositeAppearance. It contains an array of 2 appearances: an NSAquaAppearance or NSDarkAquaAppearance and an NSSystemAppearance.   Two private properties of NSAquaAppearance/NSDarkAquaAppearance are of interest: _tintColor and _cachedNormalizedBezelTintColor. These properties seem to set the color of standard controls. In my problematic application, _tintColor returns the system blue accent color. In other applications without these problems, _tintColor points to the color defined in the asset catalog. _cachedNormalizedBezelTintColor seems derived from _tintColor.  Using key-value coding, I am able to modify these properties and change the appearance of most but not all controls, buttons, and selections. However, I do not want to use private properties and this is just masking the symptom of the real problem. Has anyone experienced this problem with the global accent color? What was the solution?
4
1
1.5k
Apr ’22
EXC_CRASH (SIGABRT) on app created with py2app
I have created my first app with python using py2app and it build my app successfully but when I try to open it, it crash but when I open it's package and run it from this path: myapp.app/contents/macos/myapp it open console and run my app correctly without any error. I can't understand how to read this kind of mac errors. I will be happy if you can help me with that: Error Text
2
0
1.4k
Jul ’22
Tracking down a memory leak
I've discovered that my app has a memory leak, where when I close a window, it disappears from the screen but it (along with all its views, view controllers, and associated objects) actually doesn't get released. Instruments doesn't register it as a leak. It does show a few unidentified malloc leaks, but nowhere near enough to account for a window full of stuff. Xcode's memory graph doesn't show any leaks either, and I've combed through it looking for retain cycles or unwanted captures in blocks. I've fixed a few, but it hasn't been enough to actually get the window released. What other tactics are there for finding this kind of leak? The project is here for anyone feeling adventurous: https://github.com/Uncommon/Xit
3
0
5.8k
Aug ’22
Can't click on some areas of my apps on macOS Ventura
I've seen this issue all across the internet. I cannot click on the elements of a dropdown/combobox nor the elements of a context menu on the application I have in production for my clients. See this thread on Reddit where people complain of the same exact behaviour on other apps like Microsoft Excel or Spark: https://www.reddit.com/r/MacOSBeta/comments/xb3u0w/office_submenus_not_clickable_in_ventura_thoughts/ I've also seen on my modal windows that the events it receives apply to the parent window. For example a mouse over event will be triggered when my mouse is over the parent window when it should only be triggered when the mouse is over the modal window. Is there a thing Apple will fix before the official macOS Ventura release date or there is something developers should know to fix it by ourselves? This is kinda serious. Please help. Thanks a lot.
4
0
1.3k
Sep ’22
AppKit API to check whether Stage Manager is turned on for conditional behaviour?
Hello! Since the Stage Manager now occupies a set of interactions left of the screen to display a new dock, we'd like to conditionally turn off features or provide a feature workaround to not conflict with this set of interactions. Is there any way to check in AppKit, whether Stage Manager is currently turned on in the system to accomplish this? Any help would be greatly appreciated!
1
0
1.1k
Nov ’22
NSOpenPanel returning immediately in MacCatalyst
NSOpenPanel.runModal is returning before the user can select a file. It seemed to get progressively worse as the OS updated. Now with macOS Ventura 13.0 it is completely unusable. Supporting docs https://stackoverflow.com/questions/70050559/nsopenpanel-nssavepanel-runmodal-dismisses-immediately-with-cancel-but-only-on https://stackoverflow.com/questions/28478020/presenting-nsopenpanel-as-sheet-synchronously
7
0
1.4k
Nov ’22
"+[CATransaction synchronize] called within transaction" with NSOpenPanel
I'm getting these log messages: +[CATransaction synchronize] called within transaction whenever I spawn or resize and NSOpenPanel (or save panel). To investigate, I created the simplest possible test app, with no window and only this method that I override in AppDelegate.m: - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { NSOpenPanel *panel = NSOpenPanel.openPanel; panel.allowedFileTypes = @[@"public.plain-text"]; [panel beginWithCompletionHandler:^(NSModalResponse result) { }]; } This is basically all the code I added. And this still triggers the warning message above. The message is also posted whenever I resize the panel. I wasn't getting these messages before updating to Ventura. What am I doing wrong?
3
1
3k
Jan ’23
NSTextField changes its text color when users click on it under dark theme
// //  AppDelegate.swift //  HelloCocoa // import Cocoa @main class AppDelegate: NSObject, NSApplicationDelegate {     func applicationDidFinishLaunching(_ aNotification: Notification) {                  let myAlert = NSAlert()         myAlert.messageText = "Alert Title"         let messageAttributedString = NSAttributedString(string: "Hello,world", attributes: [.font : NSFont.systemFont(ofSize: 12, weight: .bold)])         let myTextField = NSTextField(labelWithAttributedString: messageAttributedString)         myTextField.allowsEditingTextAttributes = true         myTextField.isSelectable = true         myAlert.accessoryView = myTextField         myAlert.runModal()     }     func applicationWillTerminate(_ aNotification: Notification) {         // Insert code here to tear down your application     }     func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {         return true     } } The alert appears like this: but when I clicks on the textfield, the text's color become black: Adding foregroundColor key to attribute dictionary works for me but I really want to know why NSTextfield has such behavior
1
1
592
Jan ’23
Exception: NSView this class is not key value coding-compliant for the key cell shortly after presenting UIDocumentPickerViewController on Mac Catalyst
Shortly after presenting a UIDocumentPickerViewController on Mac Catalyst the system throws this exception and I keep hitting my exception breakpoint: NSView: valueForUndefinedKey this class is not key value coding-compliant for the key cell. Appears to be related to the system using Touch Bar APIs (my app isn't currently using Touch Bar APIs directly but the NSOpenPanel created by UIDocumentPickerViewController is). #2 0x0000000198de2828 in -[NSObject(NSKeyValueCoding) valueForUndefinedKey:] () #3 0x000000019884ef3c in -[NSObject(NSKeyValueCoding) valueForKey:] () #4 0x0000000200b75a68 in -[NSObject(UIAccessibilitySafeCategory) __axValueForKey:] () #5 0x0000000200b75960 in __57-[NSObject(UIAccessibilitySafeCategory) safeValueForKey:]_block_invoke () #6 0x0000000200b75f9c in -[NSObject(UIAccessibilitySafeCategory) _accessibilityPerformSafeValueKeyBlock:withKey:onClass:] () #7 0x0000000200b754d0 in -[NSObject(UIAccessibilitySafeCategory) safeValueForKey:] () #8 0x0000000222206b60 in -[NSTouchBarItemAccessibility__UIKit__AppKit _accessibilityPopulateAccessibiltiyInfoFromUIKit] () #9 0x0000000222206b1c in -[NSTouchBarItemAccessibility__UIKit__AppKit _itemViewMinSize:maxSize:preferredSize:stretchesContent:] () #10 0x000000019b3f70bc in -[NSCompressionGroupLayout item:minSize:maxSize:preferredSize:] () #11 0x000000019aff24f4 in -[NSTouchBarItemContainerView _updateMeasuredSizes] () #12 0x000000019aff2358 in -[NSTouchBarItemContainerView minSize] () #13 0x000000019accae98 in -[NSTouchBarLayout _aggregateWidthOfItems:sharesLeftEdge:sharesRightEdge:widthMeasurement:] () #14 0x000000019accb22c in -[NSTouchBarLayout _attributesOfItems:centerItems:givenSize:sharesLeftEdge:sharesRightEdge:xOrigin:] () #15 0x000000019acca930 in -[NSTouchBarLayout attributesOfItems:centerItems:givenSize:] () #16 0x000000019b52bbb0 in -[NSTouchBarView _positionSubviews] () #17 0x000000019b52ba6c in -[NSTouchBarView layout] () -- The exception does get caught (my app doesn't crash) but I hit the exception breakpoint over and over again while the NSOpenPanel is on screen which is annoying.
3
0
906
Jan ’23
AirPlay with AVPlayer/MPNowPlayingInfoCenter doesn't show album art on device
I'm developing a media player for Mac (AppKit, not Catalyst) that plays local and remote content. I have AirPlay working with AVPlayer (with an AVRoutePickerView assigning the route), but while I get the metadata that I've set for the MPNowPlayingInfoCenter on the AirPlay device (a TV in this case), I don't get any album art (but I do in the macOS now playing menu bar/control centre applet). It looks like this: (imgur link because I can't get it to upload in the forum): https://i.imgur.com/2JBIYCw.jpg My code for setting the metadata:         NSImage *artwork = [currentTrack coverImage];         CGSize artworkSize = [artwork size];         MPMediaItemArtwork *mpArtwork = [[MPMediaItemArtwork alloc] initWithBoundsSize:artworkSize requestHandler:^NSImage * _Nonnull(CGSize size) {             return artwork;         }];         [songInfo setObject: mpArtwork forKey:MPMediaItemPropertyArtwork]; I noticed that it doesn't resize, but it seems at least macOS doesn't care. I tried modifying the code to resize the artwork in the callback, but that also doesn't change anything. I noticed in the logs that I get a message about a missing entitlement: 2023-01-29 14:00:37.889346-0400 Submariner[42682:9794531] [Entitlements] MSVEntitlementUtilities - Process Submariner PID[42682] - Group: (null) - Entitlement: com.apple.mediaremote.external-artwork-validation - Entitled: NO - Error: (null) ...however, this seems to be a private entitlement and the only reference I can find to it is WebKit. Using it makes LaunchServices very angry at me, and I presume it's a red herring.
3
1
2.2k
Jan ’23
A VZMacGraphicsDisplayConfiguration with a large resolution causes macOS Ventura to incorrectly draw its menu bar items.
Filed as rdar://FB11975037 When macOS Ventura is run as a guest OS within the virtualization framework, the main menu bar items will not be displayed correctly if VZMacGraphicsDisplayConfiguration defines a large resolution. The menu bar titles appear to be using the same color as the menu bar itself. When the Appearance is set to Light, the menu bar items are effectively invisible. When the Appearance is set to Dark, the menu bar items are drawn in what looks like a disabled state. This only affects the menu bar item titles on the left-hand side. The date-time and menu bar icons on the right side are always displayed in the correct color. This appears to be a regression in macOS Ventura as this issue is not present in macOS 12 running as a guest. This bug can be easily reproduced using Apple's own Virtualization sample code titled: "Running macOS in a Virtual Machine on Apple Silicon Macs" Steps to reproduce: Follow the sample code instructions for building and installing a VM.bundle. Before running 'macOSVirtualMachineSampleApp', change the VZMacGraphicsDisplayConfiguration to use: width = 5120, height = 2880, ppi = 144. Run 'macOSVirtualMachineSampleApp' and notice that the menu bar titles on the left side of the screen are not correctly drawn in the guest instance. This has been tested on: Host: macOS 13.1 Guest: macOS 13.x (All versions) Hardware: MBP 14" M1 Pro 32GB/2TB Is there anything that can be done to resolve this issue?
4
2
1.2k
Jan ’23
Cursor Disappearing with Multiple NSTextViews
I have a Mac app, Notenik, written with AppKit, that dynamically generates an Edit view that is used to edit multiple fields for a Note. Sometimes, depending on a user's request, multiple NSTextViews end up appearing within the same parent view (a tab, if that matters). Lately I and some of my users have noticed that, when moving from one NSTextView to another (either by tabbing or by clicking), the cursor initially fails to appear. Once the user starts editing within the NSTextView, the cursor appears and acts normally. And this doesn't occur when moving from an ordinary text field to an NSTextView -- only when moving from one NSTextView to another. But it is troubling and confusing to users that the cursor initially disappears. I'm not sure exactly when this started happening, but it has not been happening for very long. Although I make frequent updates to the app, this section of code has had no recent changes, so I am at a loss to explain this behavior, or to correct it. Any help would be appreciated.
1
0
817
Jun ’23
How to override NSTextLayoutFragment.textLineFragments properly?
I am trying to add custom attributes on-the-fly. To make it work, I subclassed NSTextLayoutFragment, and overrode .textLineFragments property to return custom made NSTextLineFragment objects. But if I override it, TextKit2 no longer render the text and selection also doesn't work. It's same even if provide NSTextLineFragment with exactly same properties (attributed string and range). In WWDC 22 video, you told me that NSTextLayoutFragment and NSTextLineFragment are all immutable and have value semantics. But it doesn't work with different object, therefore seems still have very strong reference semantics. How to make it work with custom attributes? P.S. I also reported this as a feedback -- https://feedbackassistant.apple.com/feedback/12443016
1
1
949
Jun ’23