Is there any way to tell if the user clicked X button in windowWillClose delegate method?
- (void)windowWillClose:(NSNotification *)notification
AppKit
RSS for tagConstruct and manage a graphical, event-driven user interface for your macOS app using AppKit.
Post
Replies
Boosts
Views
Activity
I am unfortunately faced with a large legacy code base in which Storyboards are heavily used. Now, for some reason, the entire app window is resized if a certain View Controller becomes visible.
The issue: Apparently, there aren't any conflicting layout constraints (no LAYOUT_CONSTRAINTS_NOT_SATISFIABLE errors are raised on display of the view controller).
There are also no calls to setFrame on the corresponding window.
So, how do I debug this? Capturing the view hierarchy didn't provide any helpful insights, and ideally I could just force the window to not resize (due to possible constraint errors).
Is there any way to achieve something like this? If not, how can I go about debugging this?
Any help on this would be greatly appreciated.
In our Mac Catalyst app running on macOS, the Edit > Spelling and Grammar > Check Spelling While Typing, Check Grammar With Spelling, and Correct Spelling Automatically preferences are reset with each opening of a new text view. How can we make those preferences persistent? Ie, when someone changes those settings for our app's text view, other incarnations of our app's text views should respect the latest preferences.
We looked at swizzling NSTextView's toggleAutomaticSpellingCorrection:, saving those to NSUserDefaults, and then reading those preferences when we set up our UITextView subclass, and then setting the UITextInputTraits properties accordingly.
However, our approach felt heavy handed, and I'm wondering if we are missing some out-of-the-box functionality that will make those preferences intuitively persistent.
Does anyone have any suggestions? Thank you.
My Xcode workspace contains build settings for a macOS, iOS, and tvOS application.
My Sandbox macOS app builds just fine and works great - and is on the App Store.
I am in the process of creating a new build / branch of this app that is not Sandboxed so that I can add IPC (Syphon support) - as I don't think I can use App Groups to enable CFMessage support (which Syphon requires) because Syphon (third party framework) - uses its own naming convention for the ports.
Anyway, sandbox support for a Syphon app is a topic for another day (it's actually quite disappointing that I can't release a Syphon version on the App Store).
The trouble I am having, is that even afer deleting the App Sandbox entitlement from my project, my App still seems to be running in the App Sandbox, and I can't figure out how to remove the App Sandbox entitlement completely.
What I am seeing, is that even after deleting the App Sandbox entitlement (using the project settings and deleting it in the "Signing and Capabilities" tab (and also checking the entitlements file manually to doubly make sure it is gone) - I am still seeing the following error message:
*** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x8703, name = 'info.v002.Syphon.332143F7-0916-428A-A88A-59B752F95304'
See /usr/include/servers/bootstrap_defs.h for the error codes.
It is also saving my Application Support data in the ~/Library/Containers folder, and not in ~/Library/ApplicationSupport
What step am I missing?
By Implementing the TipKit framework in the AppKit Mac OS application, we were unable to close the popover when we clicked on the cross icon presented in TipNSPopover view.
And any clues about how to implement the TipNSPopover on Handover of NScollectionview ?. When the mouse enters any of the collection view cells, I have to present the TipNSpopover view.
Please share your input and thoughts.
I'd like to know how to test behavior in Swift on Desktop that needs to interact with external elements, in my case the Finder.
My goal is simple: add an option in the right-click menu of the Finder that will open my application with the selected entry or entries (file or folder) from the Finder.
I have thus set the elements NSMenuItem, NSMessage, NSPortName, NSRequiredContext (NSApplicationIdentifier: com.apple.finder) etc.
I also created a class FinderService with a function performService having this declaration:
func performService(_ pboard: NSPasteboard, userData: String, error: AutoreleasingUnsafeMutablePointer<NSString>) {
NSLog("performService called!")
}
And I instantiated my class like this: NSApplication.shared.servicesProvider = FinderService().
However, when I build and launch the application nothing happens, well my application runs fine and the instantiation of the class seems to be correctly called. But when I open my Finder, my action is not displayed in the right-click context menu. And in the logs of my application, no error appears. How can I test this?
I wanted to identify the shutdown event in macOS, so that If my application is running and the user performs a system shutdown then my application could be notified of the shutdown event and perform finalization.
I came across NSWorkspaceWillPowerOffNotification which is exactly what I require, however, I created a sample application to observe for this notification. Is is observed that right before the system shuts down, the OS terminates my application invoking applicationWillTerminate(_:) delegate and the observer method for 'NSWorkspaceWillPowerOffNotification' is not invoked.
I could perform my finalization in the applicationWillTerminate, but I wanted to know why is the observer not getting invoked. Also why is NSWorkspaceWillPowerOffNotification, even provided by apple when it invoked the termination delegate before shutdown?
below is how I m adding the observer:
NotificationCenter.default.addObserver(forName: NSWorkspace.willPowerOffNotification, object: nil, queue: nil, using: AppDelegate.handlePowerOffNotification)
Below is my observer function, which just logs:
public static func handlePowerOffNotification(_ notification: Notification) {
NSLog (AppDelegate.TAG + "System will power off soon! Perform any necessary cleanup tasks.")
// custom logger to log to a file
TWLog.Log ("System will power off soon! Perform any necessary cleanup tasks.")
}
I need to draw an outline of an Emoji glyph bounding box that is drawn in CGContext (macOS 14.4.1). I use NSLayoutManager - (void)drawGlyphsForGlyphRange:(NSRange)glyphsToShow atPoint:(NSPoint)origin; and I can get an emoji glyph bounding box using CoreText CGRect CTFontGetBoundingRectsForGlyphs(CTFontRef font, CTFontOrientation orientation, const CGGlyph *glyphs, CGRect *boundingRects, CFIndex count);. The bounding box is correct until the CGContext to which I draw the string with Emoji is not scaled or rotated. In such a case, an Emoji drawn in context is "sometimes" scaled, so its bounding box is not equal to the bounding box obtained from CoreText. Unfortunately, I can't figure out what the dependencies between glyph size, CGContext rotation, and scale are. I couldn't find any linearity between these variables. For example, an Emoji is drawn correctly at scale 6, rotation 0, when CGContext is rotated by 1 degree, Emoji is downsized by 1 pixel, then back in nominal size when rotation is between 2 and 4 degrees, then downsized for 5 degrees, nominal at 6, etc.
Has anyone solved this?
My app is crashing in CoreGraphics. As per the observations, it started crashing for Mac OS 14.4 and 14.4.1 on Arm machines. It is observed on multiple machines. Can someone please help on this?
Following is the backtrace:
Process: MyApp [1300]
Path: /Applications/MyApp.app/Contents/MacOS/MyApp
Identifier: com.MyCompany.MyApp
Version: 7.2.3 (???)
Code Type: ARM-64 (Native)
Parent Process: launchd [1]
User ID: 502
Date/Time: 2024-04-23 20:48:08.7647 +0530
OS Version: macOS 14.4.1 (23E224)
Report Version: 12
Anonymous UUID: 6DAE9C94-37AC-96D0-7221-3AAA99D9E5F6
Sleep/Wake UUID: 03812728-62F0-45A4-86FC-07E151462C11
Time Awake Since Boot: 11000 seconds
Time Since Wake: 1385 seconds
System Integrity Protection: enabled
Crashed Thread: 0 Dispatch queue: com.apple.main-thread
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000008
Exception Codes: 0x0000000000000001, 0x0000000000000008
Termination Reason: Namespace SIGNAL, Code 11 Segmentation fault: 11
Terminating Process: exc handler [1300]
VM Region Info: 0x8 is not in any region. Bytes before following region: 4338843640
REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL
UNUSED SPACE AT START
--->
__TEXT 1029d8000-1029e4000 [ 48K] r-x/r-x SM=COW /Applications/MyApp.app/Contents/MacOS/MyApp
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0 CoreGraphics 0x186aabdac shape_union + 656
1 CoreGraphics 0x186aababc shape_union_with_bounds + 128
2 CoreGraphics 0x186aab9f4 CGRegionCreateUnionWithRect + 240
3 AppKit 0x184b439dc 0x18473e000 + 4217308
4 AppKit 0x184b2ad4c 0x18473e000 + 4115788
5 AppKit 0x184dc358c -[NSViewBackingLayer setNeedsDisplayInRect:] + 176
6 AppKit 0x184790874 -[NSView setNeedsDisplayInRect:] + 396
7 Foundation 0x182070914 __NSThreadPerformPerform + 264
8 CoreFoundation 0x180f21eb0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28
9 CoreFoundation 0x180f21e44 __CFRunLoopDoSource0 + 176
10 CoreFoundation 0x180f21bb4 __CFRunLoopDoSources0 + 244
11 CoreFoundation 0x180f207a0 __CFRunLoopRun + 828
12 CoreFoundation 0x180f1fe0c CFRunLoopRunSpecific + 608
13 HIToolbox 0x18b6bb000 RunCurrentEventLoopInMode + 292
14 HIToolbox 0x18b6bae3c ReceiveNextEventCommon + 648
15 HIToolbox 0x18b6bab94 _BlockUntilNextEventMatchingListInModeWithFilter + 76
16 AppKit 0x184778970 _DPSNextEvent + 660
17 AppKit 0x184f6adec -[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 700
18 AppKit 0x18476bcb8 -[NSApplication run] + 476
19 libffi.dylib 0x191df8050 ffi_call_SYSV + 80
20 libffi.dylib 0x191e00ae0 ffi_call_int + 1212
21 _objc.cpython-39-darwin.so 0x10700a47c PyObjCFFI_Caller_SimpleSEL + 1204
22 _objc.cpython-39-darwin.so 0x107034e94 objcsel_vectorcall_simple + 768
23 Python 0x104312ddc call_function + 124
24 Python 0x104311ac0 _PyEval_EvalFrameDefault + 29288
25 Python 0x10427a720 _PyFunction_Vectorcall + 628
26 Python 0x104312ddc call_function + 124
27 Python 0x104311ac0 _PyEval_EvalFrameDefault + 29288
28 Python 0x10427a57c _PyFunction_Vectorcall + 208
29 Python 0x104312ddc call_function + 124
30 Python 0x104311a4c _PyEval_EvalFrameDefault + 29172
31 Python 0x10427a57c _PyFunction_Vectorcall + 208
32 Python 0x104312ddc call_function + 124
33 Python 0x104311ac0 _PyEval_EvalFrameDefault + 29288
34 Python 0x10427a57c _PyFunction_Vectorcall + 208
35 Python 0x104312ddc call_function + 124
36 Python 0x104311aec _PyEval_EvalFrameDefault + 29332
37 Python 0x10427a57c _PyFunction_Vectorcall + 208
38 Python 0x104312ddc call_function + 124
39 Python 0x104311aec _PyEval_EvalFrameDefault + 29332
40 Python 0x1043131a0 _PyEval_EvalCode + 620
41 Python 0x10430a7d0 PyEval_EvalCode + 80
42 MyApp 0x1029dd440 0x1029d8000 + 21568
43 MyApp 0x1029dd7c0 0x1029d8000 + 22464
44 dyld 0x180aba0e0 start + 2360
I'm trying to bind a NSProgressIndicator to Progress, but with the following code I only get an indeterminate progress indicator with a blue bar forever bouncing left and right, even after the two timers fire. According to the documentation:
Progress is indeterminate when the value of the totalUnitCount or completedUnitCount is less than zero or if both values are zero.
What am I doing wrong?
class ViewController: NSViewController {
let progress = Progress()
override func loadView() {
view = NSView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
let progressIndicator = NSProgressIndicator(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
progressIndicator.bind(.isIndeterminate, to: progress, withKeyPath: "isIndeterminate")
progressIndicator.bind(.value, to: progress, withKeyPath: "completedUnitCount")
progressIndicator.bind(.maxValue, to: progress, withKeyPath: "totalUnitCount")
progressIndicator.startAnimation(nil)
view.addSubview(progressIndicator)
progress.completedUnitCount = 3
progress.totalUnitCount = 10
Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { _ in
print(1)
self.progress.completedUnitCount = 6
}
Timer.scheduledTimer(withTimeInterval: 6, repeats: false) { _ in
print(2)
self.progress.completedUnitCount = 0
self.progress.totalUnitCount = 0
}
}
}
Our app exports a number of file types in info.plist. For each of these file types, we export various possible file name extensions. For example, for one of our file types, we specify the possible extensions ".data", ".fitdat", and ".profitdata".
In the settings of our app, we allow the user to select their preferred extension to be used, i.e. the extension to be used when, e.g., saving a document with "Save As..." panel without explicitly specifying the extension.
For this, we override NSDocument's fileNameExtensionForType:saveOperation to return the presently preferred extension.
This has stopped working, probably starting from macOS 14. If the user does not specify the extension in the NSSavePanel, it's always the first extension (".data") that gets added to the file name.
I guess it's a consequence of the introduction of UTType, which has its own preferredFilenameExtension, which in turn probably just grabs the first extension we specify in our info.plist
Any advice how to resolve this? Is there any way to override NSSavePanel's selection of extension if the user does not specify one?
Thanks for any advice in advance
Kurt
I tried doing the outlets for all the controls, then making a nsview in the method for a button that declares a view, then I set initwithframe to be sent to a variable typed 'id' and accessing that variable I was able to add nsbuttoncell to the variable, then I added the subview to the. main tableview
here's the code I used:
NSView *viewptr = [[NSView alloc]init];
NSButtonCell *bCell1 = [[NSButtonCell alloc]init];
NSRect rect;
[bCell1 setTitle:@"click"];
rect.size.width = 2;
rect.size.height = 1;
id temp,x;
temp = [viewptr initWithFrame:rect];
[temp addObject:bCell1];
[_cocoa_test_scrollview addSubview:temp];
is there anything im missing? the app keeps crashing and spiting out debug messages, like:
-[NSView addObject:]: unrecognized selector sent to instance 0x12ee0ae60
(
0 CoreFoundation 0x0000000186efaccc __exceptionPreprocess + 176
1 libobjc.A.dylib 0x00000001869e2788 objc_exception_throw + 60
2 CoreFoundation 0x0000000186fad02c -[NSObject(NSObject) __retain_OA] + 0
3 CoreFoundation 0x0000000186e64cdc forwarding + 1580
4 CoreFoundation 0x0000000186e645f0 _CF_forwarding_prep_0 + 96
5 objc_cocoa_test_image_3 0x0000000100608ca4 -[AppDelegate cocoa_test_button1_add:] + 264
6 AppKit 0x000000018a881c70 -[NSApplication(NSResponder) sendAction:to:from:] + 460
7 AppKit 0x000000018a881a74 -[NSControl sendAction:to:] + 72
8 AppKit 0x000000018a8819b8 __26-[NSCell _sendActionFrom:]_block_invoke + 100
9 AppKit 0x000000018a8818e0 -[NSCell _sendActionFrom:] + 204
10 AppKit 0x000000018a881804 -[NSButtonCell _sendActionFrom:] + 88
11 AppKit 0x000000018a87ee38 NSControlTrackMouse + 1480
12 AppKit 0x000000018a87e844 -[NSCell trackMouse:inRect:ofView:untilMouseUp:] + 144
13 AppKit 0x000000018a87e6fc -[NSButtonCell trackMouse:inRect:ofView:untilMouseUp:] + 488
14 AppKit 0x000000018a87dbd0 -[NSControl mouseDown:] + 448
15 AppKit 0x000000018a87c99c -[NSWindow(NSEventRouting) _handleMouseDownEvent:isDelayedEvent:] + 3472
16 AppKit 0x000000018a807f78 -[NSWindow(NSEventRouting) _reallySendEvent:isDelayedEvent:] + 364
17 AppKit 0x000000018a807c38 -[NSWindow(NSEventRouting) sendEvent:] + 284
18 AppKit 0x000000018aecde70 -[NSApplication(NSEventRouting) sendEvent:] + 1604
19 AppKit 0x000000018ab1b8cc -[NSApplication _handleEvent:] + 60
20 AppKit 0x000000018a6cfcdc -[NSApplication run] + 512
21 AppKit 0x000000018a6a6f54 NSApplicationMain + 880
22 objc_cocoa_test_image_3 0x0000000100608a68 main + 60
23 dyld 0x0000000186a1e0e0 start + 2360
)
can anyone point me in the right direction?
Condition: We have an existing app that runs on iPhone and iPad. We want to make it compatible with macOS, along with it we want to leverage some of the macOS native components. We achieved this using macCatalyst, but now we want to build common components using swiftUI for both macOS and iOS platforms.
Challenge: Using SwiftUI view for mac development
Approach 1:
We created a Mac bundle that contained Mac specific views (using Appkit views).
This approach worked fine for creating and using components that are specific to macOS.
Now while developing and using SwiftUI views in mac bundle we face following error -> (NSHostingViewController symbol not found).
Approach 2:
We tried creating a separate Mac app and make it part of MacCatalyst app.
In this approach we were able to show NSStatusBar and add text using SwiftUI view.
But the status bar appearance is inconsistent, sometimes NSStatusBar icon appears but other times it just won't appear.
Can anyone help with the right approach for this scenarios
In Big Sur when I use window.toolbarStyle = NSWindowToolbarStylePreference and set toolbar.displayMode = NSToolbarDisplayModeIconAndLabel the toolbar buttons don't take on the Preferences style.
The hover and click state is only over the icon when it should be a large box surrounding the icon and label. These are the normal toolbar button styles. How do I get the buttons to take on the Preferences style?
I've had to resort to using window.contentViewController = NSTabViewController to get the right toolbar button style.
Is there something special I need to do to get NSWindowToolbarStylePreference to work?
New versions of AppKit/Mac Catalyst apps that use Google's Sign In framework are being rejected by App Store Review for the past two weeks.
Reason shared was:
The user is taken to the default web browser to sign in or register for an account, which provides a poor user experience.
And also citing: Data Collection & Storage guidelines -> https://developer.apple.com/app-store/review/guidelines/#data-collection-and-storage
Opening macOS' default web browser has been a native behavior of Mac apps when using SFSafariViewController with ASWebAuthenticationSession, which is required, since iOS 13, for securely/privately logging in users.
As far as I could investigate, there hasn't been any updates to the guidelines that would indicate any required changes to developers in regards to how login works for macOS apps.
Are there any steps developers need to take to get updates approved while still providing users with Google's Sign in?
As reference, there is an on-going discussion on GoogleSignIn repo about this issue affecting multiple developers and apps:
https://github.com/google/GoogleSignIn-iOS/issues/388
I've been trying to follow the "Supporting Continuity Camera in Your Mac App" article to implement the "Import from iPhone or iPad" menu for my MacOS app. I've been able to replicate most of the article in a test AppKit application but cannot do the same in my SwiftUI application.
I'm not sure how to get the "NSMenuItemImportFromDeviceIdentifier" identifier into a SwiftUI Menu or create a NSMenu with a NSMenuItem for a SwiftUI app. I'm also not sure how to handle receiving the image in the SwiftUI environment. Any advice you might have is appreciated. Thanks!
I have a basic Xcode project where I am adding a swift file with the below AppIntent. This causes the AppIntent action to be added in the Shortcuts app in MacOS. I wanted to know how is this AppIntent directly be able to add the Intent action in the shortcuts app. I have checked the build setting in the Xcode project but I did not find anything being generated that could have caused this. Can someone help me understand what internally happens that causes the action to be added to the shortcuts app?
import AppIntents
import SwiftUI
@available(macOS 13, *)
struct TWIntent: AppIntent {
static let title: LocalizedStringResource = "TWMeditationIntent"
static var description = IntentDescription("try adding this sample action as your TW shortcut")
static var parameterSummary: some ParameterSummary {
Summary("Get information on \(\.$TWType)")
}
// we can have multiple parameter of diff types
@Parameter(title: "TWType", description: "The type to get information on.")
var TWType: String
func perform() async throws -> some IntentResult & ReturnsValue<String> & ProvidesDialog {
NSLog(AppDelegate.TAG + "Inside perform() in MeditationIntent")
return .result(value: TWType, dialog: "Logged a 15 minute break.\(TWType)")
}
}
My app uses CGEventTapCreateForPid to monitor keyboard events of a corresponding process. My app has already enabled the Accessibility permission, and AXIsProcessTrustedWithOptions returns true. However, CGEventTapCreateForPid returns null. What could be the problem? Does anyone know? I tested and found that if CGEventTapCreateForPid returns null, I can reset the Accessibility permission using tccutil reset Accessibility myapp_bundleid without restarting my app. But my app can still get the permission through AXIsProcessTrustedWithOptions
Hi,
Using purely swift programatically (no storyboard), I'm able to create an NSWindow like so:
var window = NSWindow (contentRect: pInstruction.GetFrame (),
styleMask: [.miniaturizable, .closable, .resizable, .titled],
backing: .buffered,
defer: false)
window.title = "Some Title"
window.contentViewController = MyViewController ()
let windowidentifier = NSUserInterfaceItemIdentifier ("WinID1")
window.identifier = windowidentifier
window.makeKeyAndOrderFront(nil)
This works fine and I can see a window on screen. Later, when I want to access the window I can use a utility method:
static func GetWindow(_ pWindowID: NSUserInterfaceItemIdentifier) -> NSWindow? {
let windows = NSApp.windows
for window in windows {
if window.identifier == pWindowID {
return window
}
}
return nil
}
// Then I can call this function like so:
let windowidentifier = NSUserInterfaceItemIdentifier ("WinID1")
let window = GetWindow (windowidentifier)
This also works fine.
However, if I do window.setIsVisible(false) or window.orderOut (nil) to temporarily hide the window, then NSApp.windows returns an empty array and I'm not able to find the window object and my Utility method "GetWindow ()" doesn't work.
Any suggestions on how I can find hidden windows?
Hi there,
My macOS AppKit/Cocoa app uses Swift and Objective-C, however I'm not using SwiftUI anywhere.
Customers launching the app now receive an instant crash due to dyld not being able to locate SwiftUI:
Library not loaded: /System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI
Again, not using SwiftUI anywhere in my app, cannot find any project references in Xcode that mention SwiftUI -
yet checking the generated binary with otool reveals that my app indeed appears to link against SwiftUI.
Any idea what happened..?
Thanks,
Jay