Hello.
I'm trying to change my SwiftUI Mac app icon's menu in the Dock, using the NSApplicationDelegate's applicationDockMenu(_ : ) function.
However, it does not work: The delegate function is only called once, randomly after launch, and then never again, and it will not show any items in that menu I return. When I right-click the app in the Dock, only the macOS-supplied items are shown, and my App delegate function is not called.
Here's the code I use inside my NSApplicationDelegate:
func applicationDockMenu(_ sender: NSApplication) -> NSMenu? {
let men = NSMenu()
print("applicationDockMenu called")
var it = NSMenuItem(title: "Test1", action: #selector(test(_:)), keyEquivalent: "")
it.target = self
men.addItem(it)
it = NSMenuItem(title: "Test2", action: #selector(test(_:)), keyEquivalent: "")
it.target = self
men.addItem(it)
return men
}
@objc func test(_ sender: NSMenuItem) {
print("application dock menu custom item called")
}
Is there a SwiftUI modifier I should be using instead of the NSApp delegate method, or is this just not supported at this time in SwiftUI Mac apps?
Thank you,
- Matthias
AppKit
RSS for tagConstruct and manage a graphical, event-driven user interface for your macOS app using AppKit.
Post
Replies
Boosts
Views
Activity
Hello,
How do I add a keyboard shortcut to an existing menubar command in a macOS AppKit app. Specifically, I would like to make the Delete shortcut under Edit work when I press command delete.
How do I add a keyboard shortcut to the existing command?
Thanks,
Dev_101
Looking at having editable text as the detail view within a master detail interface.
There are various examples out there that show how to build the NSViewRepresentable wrapper around NSTextView.
e.g. https://developer.apple.com/forums/thread/125920
However, when I try to embed the NSViewRepresentable within a NavigationSplitView the various examples (and my own attempt) don't work properly. There seems to be a race condition competing to update the internal bindings. I also see updateNSView being called multiple times when only one event, say selection change, is called once.
Using the SwiftUI TextEditor view actually works. (it is just so limited)
When the master selected item is changed the change isn't automatically propagated through to update the Coordinator. That's because there isn't a delegate for "master did change".
Take any of the TextViews on their own (not within a split view) and they work as you would expect.
The SwiftUI TextEditor does this without any obvious connection to the master.
So the first question is: has anybody solved this type of problem? I haven't yet found a link to the solution or a discussion on the internal trick to make this work.
In principle the view structure is:
NavigationSplitView {
// master list
List(selection : $selectedItem {
}
}
content: {
TextEditor(text: $selectedItem.text) // works
// or
CustomTextView(text: $selectedItem.text)
// all examples I've found so far fail to properly display changes to the text when edited
}
My current thought is that the internal Coordinator needs to know that there has been a selection change so you can synchronise the significant change in the contents of the text binding. Again TextEditor doesn't need to know that. makeNSView is only called once, so there isn't any regeneration of the NSTextView that you could rely on.
Have tried on both macOS and iOS and see the same results.
When running my app from Xcode Umlauts are all of a sudden broken in several places. The app has been out in the public w/o similar issues for years.
For example, this is the result when entering a filename in my NSDocument-based app:
So far I could only observe the bug when launching under Sonoma from Xcode but I'm worried this might be a general issue for users of the app running the release build.
Any ideas about what happened in macOS 14.4..?
Cheers,
Jay
Recently, when I open a document in my app, it just adds a blank line to the Open Recent submenu. Attempting to select that line produces an error alert saying "The document “(null)” could not be opened. The file doesn’t exist." However, the document does appear in the global Recent Items menu. I tried rebooting. I'm not subclassing NSDocumentController or doing anything weird about opening files. Ideas?
P.S. I tried logging in to a different account, and tried changing the bundle ID. Neither helped.
I modified an InputMethodKit example (fairly recent one from github, compiled fine and worked as expected on my machine as it was) to create a window with a WKWebView and the window doesn't load. I know that loadView is getting called, but the window never appears after calling showWindow on the window controller and there is a mysterious error in the console:
bootstrap_check_in(): (os/kern) unknown error code (44c)
From googling this it seems App Sandbox related, but I think I have everything set up correctly (App Sandbox on with outgoing connections allowed)
Totally stumped, any help or ideas would be appreciated
Here's the relevant code:
View controller
import Foundation
import WebKit
import AppKit
class InputWindowViewController: NSViewController, WKUIDelegate {
var webView: WKWebView!
override func loadView() {
NSLog("LoadView")
webView = WKWebView()
self.view = webView
webView.uiDelegate = self
webView.needsDisplay = true
}
override func viewDidLoad() {
super.viewDidLoad()
webView.load(URLRequest(url: URL(string:"https://www.apple.com")!))
}
}
Window controller
import AppKit
import Foundation
import WebKit
class InputWindowController: NSWindowController {
var controller: InputWindowViewController?
override init(window: NSWindow?) {
controller = nil
super.init(window: window)
}
override func loadWindow() {
self.window = NSWindow(contentViewController: controller!)
}
required init?(coder: NSCoder) {
controller = nil
super.init(coder: coder)
}
}
AppDelegate
import Cocoa
import InputMethodKit
import WebKit
// Necessary to launch this app
class NSManualApplication: NSApplication {
private let appDelegate = AppDelegate()
override init() {
super.init()
self.delegate = appDelegate
}
required init?(coder: NSCoder) {
// No need for implementation
fatalError("init(coder:) has not been implemented")
}
}
@main
class AppDelegate: NSResponder, NSApplicationDelegate {
var server = IMKServer()
var candidates = IMKCandidates()
var inputWindowController = InputWindowController()
func applicationDidFinishLaunching(_ notification: Notification) {
// Insert code here to initialize your application
server = IMKServer(name: Bundle.main.infoDictionary?["InputMethodConnectionName"] as? String, bundleIdentifier: Bundle.main.bundleIdentifier)
inputWindowController = InputWindowController()
inputWindowController.controller = InputWindowViewController()
inputWindowController.loadWindow()
inputWindowController.showWindow(self)
candidates = IMKCandidates(server: server, panelType: kIMKSingleRowSteppingCandidatePanel, styleType: kIMKMain)
NSLog("tried connection")
}
func applicationWillTerminate(_ notification: Notification) {
// Insert code here to tear down your application
}
}
This code is probably awful in a lot of other ways I don't realize, but I wanted to get a webview window up before I put a bunch of time into this thing
XCode 13.4
MacoOS 12.7.4
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
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?
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
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)")
}
}
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!
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
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?
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
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?
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'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
}
}
}
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 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?
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.")
}