here's my case, i develop a control widget, user can push a controlwidget to play music without open the app.
i bind a AudioPlaybackIntent to the widget. when user click the widget, the app will receive the intent and start to play music.
it works perfect when app running in background or foreground. but when app not launched, the respond is too slow, it takes several seconds to start play music.
is there any way to make the respond faster when app not launched? if i want to do something when app not launched, what should i do?
AppKit
RSS for tagConstruct and manage a graphical, event-driven user interface for your macOS app using AppKit.
Post
Replies
Boosts
Views
Activity
If anyone there is familiar with Cocoa, can you please help with the following issue: How to make the NSWindow resize based on the contentView? Here is a video of the problem: https://drive.google.com/file/d/19LN98xdF9OLcqRZhMJsGGSa0dgMvj_za/view?usp=sharing
Thanks!
This issue happens in my app and I don't know why, I cannot get even useful info from stack. it's all about AppKit and HIToolBox or CoreFoundation.
I initially suspect it might be related to NSTimer. However I think this wouldn't cause such a crash. I am currently out of ideas and unable to provide more detailed and effective information (if I could, that would be great, and I also hope to have it).
I search Apple Doc and it tell me NSInternalInconsistencyException occurs when an internal assertion fails and implies an unexpected condition within the called code. So I want to get some clues from you why I encounter such an issue.
@interface MyApp () {
scoped_refptr<base::SequencedTaskRunner> task_runner_;
}
@implementation MyApp
//...
- (void)start {
// ...
self.timer = [NSTimer
scheduledTimerWithTimeInterval:60 // call every 60 sec
target:self
selector:@selector(logAndKill:)
userInfo:info
repeats:YES];
- (void)logAndKill {
if (needLog) {
// ...
} else {
task_runner_->PostTask(FROM_HERE, base::BindOnce(^() {
[self.timer invalidate];
self.timer = nil;
}));
Dear all,
I'm building my first MacOs app.
I've created my app icon and add it to AppIcon folder, but when I'm building the application the icon shows in the dock of the screen with no rounded borders like all the other apps.
I'm attaching here the icon and as you can see it has sharp edges. It is the same way in which it shows on the dock.
Why? Has anybody experienced the same?
Thanks for the support in advance,
A.
i init a CPAlertTemplate with a CPAlertAction, on iOS17, action can called by button click, but on iOS18, action can not be called by button click.
so i can't dissmiss the alert by button click.
We are developing a lightweight VPN client inside a daemon process that will run even when no user session is active on machine. The lightweight VPN runs in machine context and does not require user session. We would like to display some basic diagnosis information about our lightweight client on macOS login window before user is logged into their machine (in case users need that).
So, is it possible to display a UI window on login screen with some basic info that user can interact with. If yes, where can I get started?
Please note, this is not an authorization plugin. We are just wanting to display info about our process that runs a lightweight VPN client on macOS login screen.
I have a textfield in accessory view of NSSavePanel. For user convenience there are default actions supported natively by macOS (such as pressing Enter, keyEquivalent). However this doesn't work for enter under Sonoma. Escape key works. Is enter keypress dangerous for malicious actors so it's not supported? I have workaround below but I am not confident if I am not violating sandbox (future proof).
Original code demonstrating the issue:
class ViewController: NSViewController, NSTextFieldDelegate, NSControlTextEditingDelegate {
let savePanel = NSSavePanel()
override func viewDidLoad() {
super.viewDidLoad()
let customView = NSView()
let textField = NSTextField(string: "11111111")
textField.delegate = self // to get focus using tab keypress
savePanel.accessoryView = textField
}
override func viewWillAppear() {
savePanel.runModal()
}
}
Workaround:
// variable set to true in delegate method controlTextDidEndEditing
var didUseTextFieldWithEnterPressed = false
override func performKeyEquivalent(with event: NSEvent) -> Bool {
if #unavailable(macOS 14) {
return super.performKeyEquivalent(with: event)
}
guard let panel, didUseTextFieldWithEnterPressed == true, event.type == .keyDown &&
(event.keyCode == UInt16(kVK_Return) || event.keyCode == UInt16(kVK_ANSI_KeypadEnter)) else {
return super.performKeyEquivalent(with: event)
}
return panel.performKeyEquivalent(with: event)
}
The documentation states that the NSApplicationDelegate function application:openURLs will replace the application:openFile call. The documentation for applicationDidFinishLaunching also states that application:openFile will be called before applicationDidFinishLaunching. Is it guarenteed therefore that applicaiton:openURLs will also be called before applicationDidFinishLaunching?
Crashed: com.apple.root.user-initiated-qos.cooperative
0 Foundation 0x4e2a4 specialized String.withUTF8(:) + 100
1 Foundation 0x4eb8c JSONWriter.serializeString(:) + 100
2 Foundation 0x4e810 JSONWriter.serializeJSON(:depth:) + 92
3 Foundation 0x4cfd4 JSONWriter.serializeObject(:depth:) + 888
4 Foundation 0x4e914 JSONWriter.serializeJSON(:depth:) + 352
5 Foundation 0xd06fc JSONEncoder.encode(:) + 624
6 Foundation 0xd0484 dispatch thunk of JSONEncoder.encode(_:) + 56
I am hitting major road blocks in migrating one of my Obj-C-Cocoa applications away from -[NSView (un)lockFocus] and -[NSBitmapImageRep initWithFocusedViewRect:].
In a transcript of a presentation on WWDC2018 I read:
With our changes to layer backing, there's a few patterns I want to call out that aren't going to work in macOS 10.14 anymore. If you're using NSView lockFocus and unlockFocus, or trying to access the window's graphics contents directly, there's a better way of doing that. You should just subclass NSView and implement draw rect. ...
Of course, we all implemented -[NSView drawRect:] for decades now. The big question is, how can we do incremental (additional, event driven) drawing in our views, without redrawing the whole view hierarchy. This is the use case of -(un)lockFocus, and especially when drawing of the base view is computational expensive. Wo would have thought that people use -(un)lockFocus for regular drawing of the NSView hierarchy.
I tried to get away with CALayer, only to find out after two days experimenting with it, that a sublayer can only be drawn if the (expensive) main layer has been drawn before —> dead end road.
Now I am going to implement a context dependent -[NSView drawRect:]. Based on a respective instance variable, either of the (expensive) base presentation of the view or the simple additions are drawn. Is it that what Apple meant by … just subclass NSView and implement draw rect?
From the point of view of object oriented programming, using switch() in methods to change the behaviour of the object is ugly - to say the least. Any better options?
Ugly or not, in any case, I don’t want to redraw the whole view hierarchy only for moving a crosshairs in a diagram.
My actual use case is:
This application draws into a custom diagram NSView electrochemical measurement curves which may consist of a few thousands up to millions of data points. The diagram view provides a facility for moving crosshairs and other pointing aids over the displayed curves, by dragging/rolling with the mouse or the touch pad, or by moving it point by point with the cursor keys.
Diagram generation is computational expensive and it must not occur only because the crosshairs should be moved to the next data point.
So for navigating the crosshairs (and other pointing aids), a respective method locks the focus of said view, restores the background from a cache, caches the background below the new position of the crosshairs using -[NSBitmapImageRep initWithFocusedViewRect:], draws the crosshairs and finally unlocks the focus.
All this does not work anymore since 10.14.
I just noticed that NSCursor.currentSystemCursor is deprecated starting in macOS 15. What method should I now use to get information about the current system cursor, including its image?
Is it possible to only allow a single window instance on macOS?
WindowGroup/DocumentGroup allow the user to create multiple instances of a window. I'd like to only allow one, for an Onboarding sequence.
I've checked the Scene documentation - https://developer.apple.com/documentation/swiftui/scene, and it appears the only types conforming to the Scene protocol are WindowGroup, DocumentGroup and Settings. How can I create a single Window in a SwiftUI App?
An example use case:
struct TutorialScene: Scene {
var body: some Scene {
	// I don't want to allow multiple windows of this Scene!
	WindowGroup {
		TutorialView()
	}	
}
import Cocoa
class MyView: NSView {
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func becomeFirstResponder() -> Bool {
return true
}
override var acceptsFirstResponder: Bool {
return true
}
override func keyUp(with event: NSEvent) {
print("keyUp: keyCode=\(event.keyCode)")
}
// the 'CMD + q' combination will quit the app
// the 'CMD + t' combination will open a font setting window
// the 'CMD + Space' combination will toggle the spotlight search
// the 'CTRL + Space' combination will toggle the input method switching
// why this can't capture the key board event like 'CMD + Space' or 'CMD + t' or 'CMD + q'?
// or how capture those combinations regardless of the system-wide shortcuts?
override func keyDown(with event: NSEvent) {
print("keyDown: keyCode=\(event.keyCode)")
if event.modifierFlags.contains(.command) {
if event.keyCode == 49 {
print("keyDown: CMD + Space") // if the 'CMD' and 'Space' keys were pressed both, this line is not print
} else {
print("keyDown: CMD + others") // here, like 'CMD' and 'j' keys were pressed both, this line is print
}
} else if event.modifierFlags.contains(.control) {
if event.keyCode == 49 {
print("keyDown: CTRL + Space") // if the 'CTRL' and 'Space' keys were pressed both, this line is not print
} else {
print("keyDown: CTRL + others") // here, like 'CTRL' and 'j' keys were pressed both, this line is print
}
} else {
print("keyDown: CMD or CTRL is not pressed")
}
}
override func flagsChanged(with event: NSEvent) {
print(#function, event.keyCode)
}
}
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear() {
super.viewWillAppear()
let myview = MyView(frame: view.bounds)
view.addSubview(myview)
}
}
Hello,
I'm not I00% sure how to ask this, so I apologize if I word it wrong.
This is Obj-C from an older project I have. My app has a NSTableView and each cell has a button to perform and action and shows a progress bar in each cell. The issue I'm running in to is when I scroll down while a task is running the running progress bar shows running on a different cell. So if its he 2nd from the bottom and a scroll an even number of row its equivalent is now showing the progress bar.
How do I target just that one cell; making it unique?
In one of my apps, I use NSTableViewDiffableDataSource in tandem with NSFetchedResultsController, which provides the necessary snapshots. This works great in macOS 14.5.
However in latest macOS 15 betas, NSTableViewDiffableDataSource does not call the 'cellProvider' completion handler anymore when the data of a visible cell changes. When data of a visible cell changes, the didChangeContentWith method of NSFetchedResultsController is called correctly, but applying the provided snapshot doesn’t result in calling the said 'cellProvider' completion handler. This looks a rollback to the early state of this API in 2020.
It concerns this piece of code:
dataSource = NSTableViewDiffableDataSource(tableView: tableView, cellProvider: { (tableView, tableColumn, row, item) -> NSView in
// Return a cell view with data
})
Does anyone know a solution or workaround to get animated updates of visible cells working in macOS 15 beta?
Yes, applying the snapshot without animation works, but that’s not where NSTableViewDiffableDataSource is designed for.
In case an Apple engineer reads this:
Looking at the sample code associated with FB13931189, is there anything wrongly implemented that prevents calling the 'cellProvider' method for visible cells?
Is this perhaps actually a bug of NSFetchedResultsController? I’m asking this because NSCollectionViewDiffableDataSource does have a very similar problem (FB13943853).
PS
Yes, this post looks very similar to https://developer.apple.com/forums/thread/759381#759381021, because the problem is identical except that concerns NSCollectionViewDiffableDataSource.
In one of my apps, I use NSCollectionViewDiffableDataSource in tandem with NSFetchedResultsController, which provides the necessary snapshots. This works great in macOS 14.5.
However, when updating data in Core Data related to a visible item in a NSCollectionView, the NSCollectionViewDiffableDataSource no longer calls the ‘itemProvider’ closure of the diffable data source when using macOS 15 Seed 3, after applying a snapshot with animation. As a result of this, the collection view does not update visible items when the related data changes.
I’m talking about this piece of code which is no longer called when it concerns a visible item:
dataSource = NSCollectionViewDiffableDataSource<String, NSManagedObjectID>(collectionView: collectionView, itemProvider: {
// Return an NSCollectionViewItem here
})
Does anyone know a workaround or solution to get updating of visible cells working in macOS 15 Seed 3, without losing animated updates?
In case an Apple engineer is reading this:
Are there any related API changes that must be taken into account?
Is this perhaps actually a bug of NSFetchedResultsController? I’m asking this because NSTableViewDiffableDataSource does have a very similar problem in macOS 15 beta.
See also FB13943853
Hello,
I am trying to use the following code to disable the Hide option for my application :
NSApplicationPresentationOptions options = [NSApp presentationOptions];
options |= NSApplicationPresentationDisableHideApplication;
[NSApp setPresentationOptions:options];
, but it doesn't have any effect : the Hide option is still clickable :
How could I remove this option?
Thanks for any help in advance!
Problem Description:
I used Swift code to change a folder icon by calling the NSWorkspace.shared.setIcon(_:forFile:options:) method. The specific code is as follows:
NSWorkspace.shared.setIcon(coloredIcon, forFile: folderURL.path, options: [.exclude10_4ElementsIconCreationOption])
I noticed that the folder icon has been correctly changed in the Finder preview window, but the icon displayed on the desktop is still the original one.
Expected Result:
I hope the folder icon on the desktop can also be updated to display the new icon.
Solutions Tried:
I have tried restarting Finder and manually refreshing the icon cache, but the folder icon on the desktop still does not update.
Help Needed:
I would like to know if there is a way to automatically refresh the desktop folder icon cache in Swift code to ensure that the changed icon can be immediately displayed.
I am developing an application that needs to interact with active editable text boxes on macOS, similar to how Grammarly functions. Specifically, my application needs to:
Read and write text in the currently active editable text box where the keyboard input is directed.
Move the writer cursor and mark text within the text box.
Ideally, the solution should support cross-platform functionality, covering both macOS and Windows.
Does anyone know of any toolkits, libraries, or APIs that can facilitate this kind of functionality on macOS?
As the topic mentioned, I want to add a overlay window onto Apps that are in full screen mode, trying to create some blur effect on the screen. But Apple seems to treat full screen mode Apps differently as a "space."
So currently I can only apply the blur effect like this.
(This is my Desktop page)
But When it doesn't affect the full screen mode Apps.
(For example: My Xcode)
And I know some of the App down this kind of stuff. Like this
This is my current code. Hope someone can tell me how to solve it.