I want to launch a file with a specified application, and I want the launched program to immediately become the frontmost window.
I know that I can do this as follows:
[[NSWorkspace sharedWorkspace] openFile:fileName withApplication:appName];
Then, if I can get the PID of that launched application, I can then do this to make that application frontmost:
NSRunningApplication* app = [NSRunningApplication
runningApplicationWithProcessIdentifier: PID];
[app activateWithOptions: NSApplicationActivateAllWindows];
The question I have is this: what is the simplest, quickest, and most reliable way to get this application's PID right after launching, so I can make sure that this application is frontmost?
This is not as straightforward as it might appear at first glance. For example, I need a process name in order to get the PID using Carbon calls, or via the application dictionary that is accessible via NSRunningApplication. However, in the general case, I don't always know what the process name is, and in some cases, the process name is an empty string.
Furthermore, I might have other instances of this same application already running, and I want to always get the PID of the specific instance of the application that I just launched.
Can anyone suggest a definitive, 100-percent reliable way to get the currently launched application's PID?
Or alternatively, is there a way to launch a given file with a specified application such that the application always opens as the frontmost app?
Have you tried using the other version of openFile which will allow you to deactivate your application, allowing the new application to take focus?
[[NSWorkspace sharedWorkspace] openFile:fileName withApplication:appName andDeactivate:YES];
It is definitely not easy to get the PID of an application. And that's how Apple likes it.. Those cheeky bastards.
I had to write this beast just to get the PID from a full path of an app I knew was running.. Hey it's easier than parsing ps aux !
Sorry if there are some of my own private functions in there but you can get the idea of how I went about it and what I tried to avoid along the way.
+ (NSUInteger)pidFromAppPath:(NSString*)path
{
NSRunningApplication *n = [[[NSWorkspace sharedWorkspace]runningApplications] filterOne:^BOOL(NSRunningApplication *runner) {
// optional: avoid totally faceless apps and "Desk Accesory"-type background apps.
if (runner.activationPolicy == NSApplicationActivationPolicyProhibited) ||
runner.activationPolicy == NSApplicationActivationPolicyAccessory)
return nil;
id runPath = [runner valueForKeyPath:#"bundleURL"];
NSString *runString = [runPath isKindOfClass:[NSString class]]
? runPath
: [runPath isKindOfClass:NSURL.class] ? [((NSURL*)runPath) path]
: nil;
// optional: filter out Google Chrome's mockery of a once sane process-table
if ( !runString
|| [[runString lastPathComponent]contains:#"Google Chrome Helper.app"]
|| [[runString lastPathComponent]contains:#"Google Chrome Worker.app"]
|| [[runString lastPathComponent]contains:#"Google Chrome Renderer.app"] )
return nil;
return [runString isEqualToString:path] ?: nil; // This is where you actually test to see if it's the same as the string passed in, lol.
}];
return n ? [n processIdentifier] : 11000; // if 11000 you messed up.
}
And voilá... NSLOG: Pid of /Applications/Utilities/Terminal.app is 46152
Related
I want to detect at runtime of my Mac application (written in Objective-C) if the user's Mac is joined to an Active Directory Server or Open Directory Server and/or any sort of "network account server". And to read the string of that setting if it exists. That is, the the setting from the Login Options pane of the "Users & Groups" applet in Systems Preference. See picture below.
Specifically, just reading the string of the specified server would be sufficient.
What's API set should I be looking at to read this setting?
A computer can be bound to multiple network account servers at one time. To list them you could use the OpenDirectory framework by creating an ODSession and list all registered nodes.
#import <OpenDirectory/OpenDirectory.h>
...
ODSession *mySession = [ODSession defaultSession];
NSError *err;
NSArray *nodeNames = [mySession nodeNamesAndReturnError:&err];
NSLog(#"nodeNames=%#", nodeNames);
I'm bound to Mac-mini.local OpenDirectory Server, and that outputs this:
nodeNames=(
"/Contacts",
"/LDAPv3/Mac-mini.local",
"/Local/Default",
"/Search"
)
To get further information about a registered node, just create an ODNode instance from the node name in the nodeNames array and use that to query that node.
ODNode *node = [[ODNode alloc] initWithSession:mySession name:#"/LDAPv3/Mac-mini.local" error:&err];
Or, you could also create an ODNode instance of a top node, like the /LDAPv3 node, directly and just ask for it's subnodes, like this:
ODNode *node = [[ODNode alloc] initWithSession:mySession name:#"/LDAPv3" error:&error];
NSArray *subnodes = [node subnodeNamesAndReturnError:&err];
NSLog(#"subnodes=%#", subnodes);
That gave me this output:
subnodes=(
"/LDAPv3/Mac-mini.local"
)
Note: there is also -unreachableSubnodeNamesAndReturnError:
If you need more info about this framework, the documentation can be found here
I'm trying to develop an iOS app that will basically act as a GUI for a telnet session. I have finally gotten the NSStream coding to work (mostly) and now I'm trying to figure out how to create certain events based on code results. I think the way to do this would be to examine the results and run a "predicate" on them. Simple example below:
I press a button that sends a command, for example the command:
"info"
The server sends a response (which I'm currently snagging and writing in my NSLog):
Version: 1.1.1
Model: xyzabc
Whatever: whatever
Etc: etc..
How would I be able to pull that information, read it, and just take the "1.1.1" or the "xyzabc" and add it to a label in my VC?
I don't need the basics of how to add it to the label, just how to strip the correct information and stick the values into an NSString.
Thanks in advance,
Chuck
(total iOS coding NOOB)
(Edit, some code added):
if (nil != output) {
NSLog(#"%#", output);
[self messageReceived:output];
_txtLabel = output;
-(void)messageReceived:(NSString *)message {
[_messages addObject:message];
}
_txtLabel is a NSString
_messages is a NSMutableArray
oh, and the NSLog looks like this when it comes in, not sure if this is relevant..:
2014-06-27 15:22:07.930 multiSceneTest[37480:60b] Version: 1.1.1
2014-06-27 15:22:07.930 multiSceneTest[37480:60b] Model: xyzabc
2014-06-27 15:22:07.931 multiSceneTest[37480:60b] Whatever: Whatever
I want to read current user language(preferred language) and region from a daemon process in mac.
I tried the below code. It works fine while running this piece of code in user space process but it's returning "en" and "us" while this piece of code run from root/daemon process.
CFLocaleRef loc = CFLocaleCopyCurrent();
CFStringRef countryCode = (CFStringRef)CFLocaleGetValue (loc, kCFLocaleCountryCode);
CFShow(countryCode);
CFArrayRef langs = CFLocaleCopyPreferredLanguages();
CFStringRef langCode = (CFStringRef)CFArrayGetValueAtIndex (langs, 0);
CFStringRef langName = CFLocaleCopyDisplayNameForPropertyValue (loc, kCFLocaleLanguageCode, langCode);
CFShow(langCode);
What's the best way to get the current user language and region in daemon/root process in mac ?
Any help is appriciated....Thanks in advance....
well if you use NSLocale you have + (id)systemLocale
it is garanteed to have keys set where currentLocale isn't if you are running as root... I hope they are the keys you are looking for.
I'm trying to get an app's window (let's say Firefox as an example) and bring it to the very front and focus it. It works fine when the program isn't maximized, allowing me to bring any of Firefox's windows to the front.
However when maximized, it just brings the whole group of windows to the front, regardless of whether or not it was the window I specifically chose. Here's what I'm using:
AXUIElementPerformAction (element, kAXRaiseAction);
ProcessSerialNumber psn = [self serialNumberOfPid: [appPid unsignedIntValue]];
SetFrontProcessWithOptions (&psn, kSetFrontProcessFrontWindowOnly);
Reading some other posts, I've tried this:
AXUIElementSetAttributeValue(element, kAXMainAttribute, kCFBooleanTrue);
AXUIElementSetAttributeValue(element, kAXFocusedAttribute, kCFBooleanTrue);
AXUIElementPerformAction (element, kAXRaiseAction);
ProcessSerialNumber psn = [self serialNumberOfPid: [appPid unsignedIntValue]];
SetFrontProcessWithOptions (&psn, kSetFrontProcessFrontWindowOnly);
What am I doing wrong? Why does it only happen when the windows are maximized? Is there a better way of doing this?
Try using the kAXFrontmostAttribute property:
AXUIElementSetAttributeValue(element, kAXFrontmostAttribute, kCFBooleanTrue);
I have finished the majority of my application that I am working on, but I have run into a problem. Basically, what I wrote streams audio from my server to the iPod and plays it without having to save the file. It has a GUI that allows the user to choose the file they want to listen to, and it works flawlessly.
My problem is that I want to be able to have some sort of a counter that updates every time a user listens to a file. I have a file in the project, "TotalDownloads.txt," that I had planned on using to store the new value and upload back to the server, but when the code executes, nothing changes within that file. I had also tried just declaring the file #"TotalDownloads.txt," but that created a new file in the Macintosh HD named "TotalDownloads.txt."
The two identifiers "//-" and "-//" are to parse the file for the number, when I get this figured out, specifically to isolate the numeric value, should there be any formatting involved. Eventually, I want to have counts for each and every one of the files.
I have no problem with downloading the text file off of the server and reading it into the iPhone, but the problem arises when sending it back. What is the easiest way to 1, make a temporary file text file on the iPhone, and 2, upload it back to the server to replace the existing file?
Is there a way to just modify the file on the server?
Any help is appreciated.
Below is what I have so far:
- (IBAction)action
{
NSURL *textURL = [NSURL URLWithString:#"http://www.faithlifefellowship.us/Audio/TotalDownloads.txt"];
NSString *textFromFile = [NSString stringWithContentsOfURL:textURL encoding:NSUTF8StringEncoding error:false];
int click = [textFromFile intValue];
click += 1;
NSString *replace = #"//-";
NSString *clicks = [NSString stringWithFormat:#"%d",click];
replace = [replace stringByAppendingString:clicks];
replace = [replace stringByAppendingString:#"-//"];
//test is a label I used to check to make sure the download count was being read properly.
test.text = clicks;
[replace writeToFile:[[NSBundle mainBundle] pathForResource:#"TotalDownloads" ofType:#"txt"]atomically:YES encoding:NSUTF8StringEncoding error:NULL];
}
Here is the best way I suggest you do this.
Set up a page on your server that accepts a get request.
Code the page to take the value from that get request (which should be the name of the file you are trying to update) and update the file at that path.
From your app, use UIWebView this way:
UIWebView* web = [UIWebView new];
[web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.mydomain.com/myPage.php"]]];
web = nil;
Presto!