Implementing "Show in Finder" button in Objective-C - objective-c

In my application I would like to create a 'Show in Finder' button.
I have been able to figure out how to pop up a Finder window of that directory but haven't figured out how to highlight the file like the OS does.
Is this possible?

NSArray *fileURLs = [NSArray arrayWithObjects:fileURL1, /* ... */ nil];
[[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:fileURLs];
stolen from
Launch OSX Finder window with specific files selected

You can use NSWorkspace method -selectFile:inFileViewerRootedAtPath: like this:
[[NSWorkspace sharedWorkspace] selectFile:fullPathString inFileViewerRootedAtPath:pathString];

Its worth mentioning that owen's method only works from osx 10.6 or later (Ref: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSWorkspace_Class/Reference/Reference.html ).
So if your writing something to run on the older generations its probably better to do it in the way suggested by justin as its not been deprecated (yet).

// Place the following code within your Document subclass
// enable or disable the menu item called "Show in Finder"
override func validateUserInterfaceItem(anItem: NSValidatedUserInterfaceItem) -> Bool {
if anItem.action() == #selector(showInFinder) {
return self.fileURL?.path != nil;
} else {
return super.validateUserInterfaceItem(anItem)
}
}
// action for the "Show in Finder" menu item, etc.
#IBAction func showInFinder(sender: AnyObject) {
func showError() {
let alert = NSAlert()
alert.messageText = "Error"
alert.informativeText = "Sorry, the document couldn't be shown in the Finder."
alert.runModal()
}
// if the path isn't known, then show an error
let path = self.fileURL?.path
guard path != nil else {
showError()
return
}
// try to select the file in the Finder
let workspace = NSWorkspace.sharedWorkspace()
let selected = workspace.selectFile(path!, inFileViewerRootedAtPath: "")
if !selected {
showError()
}
}

Related

macOS Swift: How to properly add application as Login Item

I have spent about one day (maybe a little more) on trying to add my application to Login Item in the order it starts up at macOS launch (user login).
The first approach was the newest one; I check this tutorial on youtube:
https://www.youtube.com/watch?v=2mmWEHUgEBo&t=660s
So following this steps, I have done:
Add new project inside my main project that I have named Launcher
I am using Automatic Signing (as version of my Xcode) is different
In Project Settings > Capabilities I toggled App Sandbox to ON.
In Build Phases I have added this:
My Launcher has Skip Install = YES
Code in my Launcher app looks like this (I have even previously use Swift to do the same)
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
NSArray *pathComponents = [[[NSBundle mainBundle] bundlePath] pathComponents];
pathComponents = [pathComponents subarrayWithRange:NSMakeRange(0, [pathComponents count] - 4)];
NSString *path = [NSString pathWithComponents:pathComponents];
[[NSWorkspace sharedWorkspace] launchApplication:path];
[NSApp terminate:nil];
}
Finally, I have magic code in Main App to enable app as Login Item
if(!SMLoginItemSetEnabled("click.remotely.Remotely-Click-Server-Launcher"
as CFString, Bool(checkboxButton.state as NSNumber) ) ) {
let alert: NSAlert = NSAlert()
alert.messageText = "Remotely.Click Server - Error";
alert.informativeText = "Application couldn't be added as
Login Item to macOS System Preferences > Users & Groups.";
alert.alertStyle = NSAlertStyle.warning;
alert.addButton(withTitle:"OK");
alert.runModal();
}
I have made Archive, and then have different options to Export:
I couldn't decide which one to choose, so I tried all of them.
"Save for Mac App Store Deployment" - made Installation package that has installed in /Applications/ directory but the app never runs.
"Developer-Id signed," "Development-signed" , "macOS App" all makes file in a directory that I exported to Applications directory, but no one works.
When I click the checkbox button, I could see some window blinking for a while on the screen (Launcher program). When I log out and log in the same window blinking effect appears but Launcher didn't start the Main application. When I click checkbox button again (and turn off Login Item) this blinking effect on user login (system startup) doesn't happen again. So it seems that this addition of Launcher program as Login Item works, but this Launcher couldn't start the Main app. Moreover when I go to /Applications/Main.app/Contents/Library/LoginItems/Launcher.app and click it manually then Launcher app launch Main application correctly (so the path was correct).
So what's going wrong?
Then I consider implementation of deprecated approach using
kLSSharedFileListSessionLoginItems
I have thought it must work it just add something in System Preferences this
window below.
But it also could go wrong!
I have chosen implementation in Swift (all examples/tutorials I have found was in Objective-C) So I have written something like this:
class LoginItemsList : NSObject {
let loginItemsList : LSSharedFileList = LSSharedFileListCreate(nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil).takeRetainedValue();
func addLoginItem(_ path: CFURL) -> Bool {
if(getLoginItem(path) != nil) {
print("Login Item has already been added to the list.");
return true;
}
var path : CFURL = CFURLCreateWithString(nil, "file:///Applications/Safari.app" as CFString, nil);
print("Path adding to Login Item list is: ", path);
// add new Login Item at the end of Login Items list
if let loginItem = LSSharedFileListInsertItemURL(loginItemsList,
getLastLoginItemInList(),
nil, nil,
path,
nil, nil) {
print("Added login item is: ", loginItem);
return true;
}
return false;
}
func removeLoginItem(_ path: CFURL) -> Bool {
// remove Login Item from the Login Items list
if let oldLoginItem = getLoginItem(path) {
print("Old login item is: ", oldLoginItem);
if(LSSharedFileListItemRemove(loginItemsList, oldLoginItem) == noErr) {
return true;
}
return false;
}
print("Login Item for given path not found in the list.");
return true;
}
func getLoginItem(_ path : CFURL) -> LSSharedFileListItem! {
var path : CFURL = CFURLCreateWithString(nil, "file:///Applications/Safari.app" as CFString, nil);
// Copy all login items in the list
let loginItems : NSArray = LSSharedFileListCopySnapshot(loginItemsList, nil).takeRetainedValue();
var foundLoginItem : LSSharedFileListItem?;
var nextItemUrl : Unmanaged<CFURL>?;
// Iterate through login items to find one for given path
print("App URL: ", path);
for var i in (0..<loginItems.count) // CFArrayGetCount(loginItems)
{
var nextLoginItem : LSSharedFileListItem = loginItems.object(at: i) as! LSSharedFileListItem; // CFArrayGetValueAtIndex(loginItems, i).;
if(LSSharedFileListItemResolve(nextLoginItem, 0, &nextItemUrl, nil) == noErr) {
print("Next login item URL: ", nextItemUrl!.takeUnretainedValue());
// compare searched item URL passed in argument with next item URL
if(nextItemUrl!.takeRetainedValue() == path) {
foundLoginItem = nextLoginItem;
}
}
}
return foundLoginItem;
}
func getLastLoginItemInList() -> LSSharedFileListItem! {
// Copy all login items in the list
let loginItems : NSArray = LSSharedFileListCopySnapshot(loginItemsList, nil).takeRetainedValue() as NSArray;
if(loginItems.count > 0) {
let lastLoginItem = loginItems.lastObject as! LSSharedFileListItem;
print("Last login item is: ", lastLoginItem);
return lastLoginItem
}
return kLSSharedFileListItemBeforeFirst.takeRetainedValue();
}
func isLoginItemInList(_ path : CFURL) -> Bool {
if(getLoginItem(path) != nil) {
return true;
}
return false;
}
static func appPath() -> CFURL {
return NSURL.fileURL(withPath: Bundle.main.bundlePath) as CFURL;
}
}
I have used this to turn on/off Login Item by clicking in the checkbox
let loginItemsList = LoginItemsList();
if( checkboxButton.state == 0) {
if(!loginItemsList.removeLoginItem(LoginItemsList.appPath())) {
print("Error while removing Login Item from the list.");
}
} else {
if(!loginItemsList.addLoginItem(LoginItemsList.appPath())) {
print("Error while adding Login Item to the list.");
}
}
I have run it in Debug mode (Xcode Play button) and try to archive it and export to /Applications folder if it matters, but this approach also doesn't work.
Console-printed messaged. Error means that the function Inserting Login Item returns nil.
So after that I even try to implement this (from some stackoverflow example) using Objective-C (as there is many Unmanaged<> in Swift)
So I added new .m and .h file and Bridging-Header.h and then a code like this:
- (void)enableLoginItemWithURL:(NSURL *)itemURL
{
LSSharedFileListRef loginListRef = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
if (loginListRef) {
// Insert the item at the bottom of Login Items list.
LSSharedFileListItemRef loginItemRef = LSSharedFileListInsertItemURL(loginListRef,
kLSSharedFileListItemLast,
NULL,
NULL,
(__bridge CFURLRef) itemURL,
NULL,
NULL);
if (loginItemRef) {
CFRelease(loginItemRef);
}
CFRelease(loginListRef);
}
}
Simple (just insertion) without any bells and whistles.
It also has the same issue that LSSharedFileListInsertItemURL returns nil and Login Item is not added to System Preferences > Users & Groups > Login Items.
So any idea why I cannot make this work?
UPDATE 1
I have tried to implement application using first approach (helper Launcher application inside Main application) on another computer iMac (MacOS Sierra and the newest XCode 8.3) and it seems to work there correctly so maybe there is something wrong with my OS or Xcode (provisioning profiles, signing of app or whatever) On MacBook Air where this approach doesn't work I am using OS X El Capitan 10.11.5 and Xcode 8.0.
Watch how it works here:
https://youtu.be/6fnLzkh5Rbs
and testing
https://www.youtube.com/watch?v=sUE7Estju0U
The second approach doesn't work also on my iMac returning the nil while doing LSSharedFileListInsertItemURL. So I don't know why that is happening.
Watch how it works here:
https://youtu.be/S_7ctQLkIuA
UPDATE 2
After upgrade to macOS Sierra 10.12.5 from El Capitan 10.11.5 and using Xcode 8.3.2 instead of Xcode 8.0.0 the second approach also happens to work correctly and is adding Login Items to System Preferences > Users & Groups > Login Items
IMPORTANT! To work this approach with LSSharedFileListInsertItemURL needs to disable App Sandboxing! Like in the video below:
https://youtu.be/UvDkby0t_WI
I also struggled with this a few years ago and ended up making a package for it that makes it much easier to add "launch at login" functionality for sandboxed apps.
Instead of lots of manual steps, you just need:
import LaunchAtLogin
LaunchAtLogin.isEnabled = true
Since macOS 13 Ventura, we can finally use a new SMAppService.
import ServiceManagement
try SMAppService.mainApp.register()
See SMAppService documentation for more details.
For the ServiceManagement approach, sometimes it doesn't work in your development machine because there is another copy of the app in your Xcode's DerivedData. The system don't know which app to launch. So go to ~/Library/Developer/Xcode/DerivedData and delete your development copy could help.
The above solution of Login Item programming problem works correctly both using modern approach with ServiceManagement.framework, and old (deprecated) approach with inserting Login Item into System Preferences > Users & Groups > Login Items. See my UPDATE 1 and UPDATE 2 remarks.
Dear Michal I have had the same problem about log in items. Log in items can be added in two ways; one from LSSharedFileListItemRef which will be shown in Login item of preferences but this approach will only work for non-sandboxing app and if you are making sandbox app then you should go for another way of using ServiceManagement framework.
You can have look over below link which specify everything - :
Launching your app on system start
I am adding another reference of adding app on log in - :
Approach for sandbox app with helper application
May be you are having trouble implementing app on log in item but follow the steps appropriately and you will succeed.

How to wait for Location Alert ( which is system alert) to show?

I figured out how to dismiss System alert, but I am not able to wait for it to show , since app doesn't see System Alerts. I tried to debug with app.debugDescription and app.alerts.count but no luck.
You should use addUIInterruptionMonitor as #Oletha wrote.
The tricky part here is that system alert buttons don't use Accessibility Identifiers so you have to search for text to tap them. This text is translated to the language you're running your simulator/device, which can be hard if you want to run the test for several languages beside English.
You could use AutoMate framework to simplify this. Here you have an example how to deal with system alerts using AutoMate:
func locationWhenInUse() {
let token = addUIInterruptionMonitor(withDescription: "Location") { (alert) -> Bool in
guard let locationAlert = LocationWhenInUseAlert(element: alert) else {
XCTFail("Cannot create LocationWhenInUseAlert object")
return false
}
locationAlert.allowElement.tap()
return true
}
// Interruption won't happen without some kind of action.
app.tap()
// Wait for given element to appear
wait(forVisibilityOf: locationPage.requestLabel)
removeUIInterruptionMonitor(token)
}
In the example above the locationAlert.allowElement.tap() is possible because AutoMate can handle any language supported by iOS Simulator.
For more examples on how to deal with system alerts using AutoMate please look into: PermissionsTests.swift
Use addUIInterruptionMonitor:withDescription:handler: to register an interruption monitor. To 'wait' for the system alert to appear, use the handler to set a variable when it has been dealt with, and execute a benign interaction with the app when you want to wait for the alert.
You must continue to interact with the app while you are waiting, as interactions are what trigger interruption monitors.
class MyTests: XCTestCase {
let app = XCUIApplication()
func testLocationAlertAppears() {
var hasDismissedLocationAlert = false
let monitor = addUIInterruptionMonitor(withDescription: "LocationPermissions") { (alert) in
// Check this alert is the location alert
let location = NSPredicate(format: "label CONTAINS 'Location'")
if alert.staticTexts.element(matching: location).exists {
// Dismiss the alert
alert.buttons["Allow"].tap()
hasDismissedLocationAlert = true
return true
}
return false
}
// Wait for location alert to be dismissed
var i = 0
while !hasDismissedLocationAlert && i < 20 {
// Do some benign interaction
app.tap()
i += 1
}
// Clean up
removeUIInterruptionMonitor(monitor)
// Check location alert was dismissed
XCTAssertTrue(hasDismissedLocationAlert)
}
}

NSSearchField with menu not being updated

I haev a Document Based Application, and In the document view, I have a NSSearchField. In the search field, I have enabled the menu, which I get to show up, and I have associated actions with the menu item. One of the menu items is called "Match Case". I want to be able to put (and remove) a check next this menu item. When I attempt to do so, the menu does not show the check.
-(IBAction)searchMenuMatchCase:(id)sender {
NSMenuItem *smi = [searchMenu itemWithTitle:#"Match Case"];
if (searchCaseSensitive) {
searchCaseSensitive = false;
[[searchMenu itemWithTitle:#"Match Case"] setState:NSOffState];
} else {
searchCaseSensitive = true;
[[searchMenu itemWithTitle:#"Match Case"] setState:NSOnState];
}
[searchMenu update];
NSLog(#"SM State %ld",[smi state]);
}
The code gets executed, and I get a log message showing the state going from 0 to 1 to 0 to 1. But there is never a check next to the menu item. When I look at the menu item object while debugging, I do see the "state" value set to 0 and 1 before I toggle it.
Any suggestions as to what I am missing?
To get around this issue, I had to use the NSMenuDelegate and use the method validateMenuItem. This way the validateMenuItem method was called before the menu was drawn, and I could make sure the state was set correctly before the menu was drawn. I believe what was happening was that the menu item I was getting in the original code was not the actual menu that was being drawn, but just a template.
/**
This is called when the user selectes the "Match Case" menu item found in the Search field
*/
-(IBAction)searchMenuMatchCase:(id)sender {
if (searchCaseSensitive) {
searchCaseSensitive = false;
} else {
searchCaseSensitive = true;
}
}
/**
This is called Each time a menu is shown.
*/
-(BOOL) validateMenuItem:(NSMenuItem *)menuItem {
if ([[menuItem title] compare:#"Match Case"] == 0) {
if (searchCaseSensitive) {
[menuItem setState:NSOnState];
} else {
[menuItem setState:NSOffState];
}
}
return YES;
}

How to change PreferredStatusBarStyle programmatically

I'd like to change the color of status bar from white to black by press button, programmatically only in a single-ViewController
This is the code:
- (UIStatusBarStyle)preferredStatusBarStyle {
NSLog(#"PreferredStatusBarStyle");
if(nav_bar.alpha==1)
{
NSLog(#"->UIStatusBarStyleBlackOpaque");
return UIStatusBarStyleBlackOpaque;
}
else
{
NSLog(#"->UIStatusBarStyleLightContent");
return UIStatusBarStyleLightContent;
}}
then When I press a button action is:
[self setNeedsStatusBarAppearanceUpdate];
But this doesn't work!
When I press the button log write the correct status according to navbar.alpha, but statusbar text color remain UIStatusBarStyleBlackOpaque like when view appear.
setStatusBarStyle:animated: has been deprecated. In iOS9 you can achieve the same thing using preferredStatusBarStyle and setNeedsStatusBarAppearanceUpdate.
In your View Controller:
override func preferredStatusBarStyle() -> UIStatusBarStyle {
if (condition) {
return .LightContent
}
return .Default
}
And then when your condition changes:
self.setNeedsStatusBarAppearanceUpdate()
On Swift 4:
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
Hope it helps anybody else to find this post.
what you need to do, is to call the -setStatusBarStyle:animated: method thru the shared application, like this
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
you can use it without the animated parameter as well. keep in mind that UIStatusBarStyleBlackOpaque is deprecated in iOS 7, documentation says you wanna use UIStatusBarStyleLightContent instead
edit:
sorry, if u wanna use preferredStatusBarStyle, take a look at this preferredStatusBarStyle isn't called

How to check if Option key is down when user clicks a NSButton

I have a few checkboxes along with textfields on a NSPanel that opens to get user parameters.
As an option, I'd like the user to be able to set/unset all the checkboxes on the panel by holding the option key when they press any of the checkboxes.
I'm not sure where/how to check what the key board is doing when the user clicks the button.
check [NSEvent modifierFlags]...
if ([NSEvent modifierFlags ] & NSAlternateKeyMask)
{
//do something
}
Just my 2c, a Swift 3 version:
if NSEvent.modifierFlags().contains(NSEventModifierFlags.command) {
print("Bingo")
}
One can see the rest of the flags in the documentation for NSEventModifierFlags.
Update: NSAlternateKeyMask is now deprecated. Use NSEventModifierFlagOption instead.
See NSEventModifierFlags for a complete overview about all modifier flags.
Swift 5 - Also helps distinguish between the "up" and "down" presses of Option key
override func flagsChanged(with event: NSEvent) {
print(event)
if event.keyCode == 58 && event.modifierFlags.contains(NSEvent.ModifierFlags.option){
print("Option Key is down!")
}
else if(event.keyCode == 58)
{
print("Option Key is up!")
}
}
Swift 2.2:
if NSEvent.modifierFlags().contains(.AlternateKeyMask) {
print("Option key pressed")
}
It's for someone who using swift and struggling with this.
if NSEvent.modifierFlags.rawValue & NSEvent.ModifierFlags.command.rawValue != 0 {
// to do something.
}
On macOS 10.14, when called from a NSGestureRecognizerDelegate method in ObjC, [NSEvent modifierFlags] was always returning 0 for me, regardless of what keys were down. I was able to reliably work around this by using [NSApp currentEvent] instead of NSEvent.
- (BOOL)isOptionKeyDown {
NSEventModifierFlags keyEventFlags = [[NSApp currentEvent] modifierFlags] & NSEventModifierFlagDeviceIndependentFlagsMask;
return (keyEventFlags & NSEventModifierFlagOption) != 0;
}
Swift 4:
func optionKeyPressed() -> Bool
{
let optionKey = NSEvent.modifierFlags.contains(NSEvent.ModifierFlags.option)
return optionKeyPressed
}
if optionKeyPressed()
{
print ("option key pressed")
}