How do I programmatically open an OS X app (.app) that is contained within the app I am building?
The preferred way of doing this on OS X is through the NSWorkspace class, which provides a couple of methods to launch applications. One of them, launchApplicationAtURL:options:configuration:error: allows you to specify a file URL to the application to launch. In addition of not having sandbox problems like the system() and Apple Event solution, it also gives you an easy way to manipulate how the application should be launched, eg. you can specify environment variables to be passed to the application.
Following Code snippet is used to launch an app programmatically:
NSString *path = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];
path = [path stringByAppendingString:#"/MyApp.app"]; // App Path
NSWorkspace *ws=[NSWorkspace sharedWorkspace];
NSURL* url = [NSURL fileURLWithPath:path isDirectory:NO];
[ws launchApplicationAtURL:url
options:NSWorkspaceLaunchWithoutActivation
configuration:nil
error:nil];
You could use an Apple Script.
NSDictionary* errorDict;
NSAppleEventDescriptor* returnDescriptor = NULL;
NSAppleScript* scriptObject;
scriptObject = [[NSAppleScript alloc] initWithSource:#"try\n
run application \"Macintosh HD:Applications:_Sandbox-AppleScript0.app\"\n
on error number -609 # 'Connection is invalid' error that is spuriously reported # simply ignore\n
end try"];
if (returnDescriptor != NULL) {
// successful execution
if (kAENullEvent != [returnDescriptor descriptorType]) {
// script returned an AppleScript result
if (cAEList == [returnDescriptor descriptorType]) {
// result is a list of other descriptors
}
else {
// coerce the result to the appropriate ObjC type
}
}
}
Related
How does one programatically set the iTunes library location on macOS to custom locations using e.g. C / Obj-C or Swift API?
Alternatively, environmental settings, such as modifying plists, using the defaults CLI tool, or similar approaches, are also OK for me.
Ordinarily, selecting a custom iTunes library location is done by launching iTunes while holding down the option key. I need to be able to do this in e.g. a unit testing environment / programatically.
You may be able to set it via the prefs.
This is how I access it.
-(void)loadITunesPrefLibraryPath {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary *userPref = [userDefaults persistentDomainForName:#"com.apple.iTunes"];
id dataBaseLoc = [userPref objectForKey:#"Database Location"];
NSLog(#"%s dataBaseLoc is:%#", __PRETTY_FUNCTION__, dataBaseLoc);
NSLog(#"%s dataBaseLoc class is:%#", __PRETTY_FUNCTION__, [dataBaseLoc class]);
NSData* dataBaseData = (NSData*)dataBaseLoc;
BOOL staleBook = NO;
NSError* bookError = nil;
NSURL* dataBaseURL = [NSURL URLByResolvingBookmarkData:dataBaseData options:NSURLBookmarkResolutionWithoutMounting relativeToURL:nil bookmarkDataIsStale:&staleBook error:&bookError];
self.libExtDBfile = dataBaseURL;
}
Once you get the userPrefs for iTunes.
And create a BookMarkData from URL.
You might be able to set it via
[userPref setObject:newDataBaseLoc forKey:#"Database Location"];
also see next answer for possible ITLibrary framework private API access
I'm programming an OS X application and would like to know what is considered to be the best location to store application data like config-files and plugins for my program into.
The configs aren't in defaults format since I also deploy this application on Windows.
Usually in your app's subfolder within the Application Support directory is where stuff like is expected to be stored. Apple provides a nice function in their documentation for getting a standardized NSURL for your Application Support directory.
Extracted from their documentation:
- (NSURL*)applicationDirectory
{
NSString* bundleID = [[NSBundle mainBundle] bundleIdentifier];
NSFileManager*fm = [NSFileManager defaultManager];
NSURL* dirPath = nil;
// Find the application support directory in the home directory.
NSArray* appSupportDir = [fm URLsForDirectory:NSApplicationSupportDirectory
inDomains:NSUserDomainMask];
if ([appSupportDir count] > 0)
{
// Append the bundle ID to the URL for the
// Application Support directory
dirPath = [[appSupportDir objectAtIndex:0] URLByAppendingPathComponent:bundleID];
// If the directory does not exist, this method creates it.
// This method is only available in OS X v10.7 and iOS 5.0 or later.
NSError* theError = nil;
if (![fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES
attributes:nil error:&theError])
{
// Handle the error.
return nil;
}
}
return dirPath;
}
You can call the subpath within NSApplicationDirectory anything you want, but they recommend using your bundle identifier, as seen in the example above.
I want to open a URL in Cocoa through my app in Safari only. I am using:
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString: #"my url"]];
But the problem is that if my default browser is not Safari, then the URL gets open in some other browser. But I want my URL to open in Safari only. Please tell the solution.
Thanks :)
let url = URL(string:"https://twitter.com/intent/tweet")!
NSWorkspace.shared.open([url],
withAppBundleIdentifier:"com.apple.Safari",
options: [],
additionalEventParamDescriptor: nil,
launchIdentifiers: nil)
Use NSWorkspace's openURLs(_:withAppBundleIdentifier:options:additionalEventParamDescriptor:launchIdentifiers:):
let url = NSURL(string:"http://example.com")!
let browserBundleIdentifier = "com.apple.Safari"
NSWorkspace.sharedWorkspace().openURLs([url],
withAppBundleIdentifier:browserBundleIdentifier,
options:nil,
additionalEventParamDescriptor:nil,
launchIdentifiers:nil)
Use scripting bridge with safari to open a URL in safari, You will find a method to open url in the file Safari.h.
To know more about using Scripting bridge refer the link and to use scripting bridge with safari and generate Safari.h, refer my answer here.
The method to open a URL in Safari is:
NSDictionary *theProperties = [NSDictionary dictionaryWithObject:#"https://www.google.co.in/" forKey:#"URL"];
SafariDocument *doc = [[[sfApp classForScriptingClass:#"document"] alloc] initWithProperties:theProperties];
[[sfApp documents] addObject:doc];
[doc release];
You can't use URL, you need a NSString
if(![[NSWorkspace sharedWorkspace] openFile:fullPath
withApplication:#"Safari.app"])
[self postStatusMessage:#"unable to open file"];
To open a URL with any application, you can use the launch services.
The function you want to look at is LSOpenURLsWithRole ;
EDIT:
You will have to link the SystemConfiguration framework to your project for this method to be available.
Apple doc reference here
For example if you want to open http://www.google.com with safari :
//the url
CFURLRef url = (__bridge CFURLRef)[NSURL URLWithString:#"http://www.google.com"];
//the application
NSString *fileString = #"/Applications/Safari.app/";
//create an FSRef of the application
FSRef appFSURL;
OSStatus stat2=FSPathMakeRef((const UInt8 *)[fileString UTF8String], &appFSURL, NULL);
if (stat2<0) {
NSLog(#"Something wrong: %d",stat2);
}
//create the application parameters structure
LSApplicationParameters appParam;
appParam.version = 0; //should always be zero
appParam.flags = kLSLaunchDefaults; //use the default launch options
appParam.application = &appFSURL; //pass in the reference of applications FSRef
//More info on params below can be found in Launch Services reference
appParam.argv = NULL;
appParam.environment = NULL;
appParam.asyncLaunchRefCon = NULL;
appParam.initialEvent = NULL;
//array of urls to be opened - in this case a single object array
CFArrayRef array = (__bridge CFArrayRef)[NSArray arrayWithObject:(__bridge id)url];
//open the url with the application
OSStatus stat = LSOpenURLsWithRole(array, kLSRolesAll, NULL, &appParam, NULL, 0);
//kLSRolesAll - the role with which the applicaiton is to be opened (kLSRolesAll accepts any)
if (stat<0) {
NSLog(#"Something wrong: %d",stat);
}
spawning a process and executing open -a "Safari" http://someurl.foo also does the trick
I've written this code below just to get it to compile but this will not work, because I need to have a deployment target of 10.8.
what is going on is I need access to EKEventStore , so when someone downloads this app, it runs fine in 10.8, but someone downloading in 10.9 would get errors, because the app doesn't have Privacy permission to the calendar. Since it is being compiled for 10.8, it has no access to the method requestAccessToEntityType:EKEntityTypeEvent..
how would one go about doing this?
on a related note, how do you compile code for 10.9, other code for 10.8, and call those different parts depending on the environment it is in? remembering this is for the Mac App Store, and if that is the way to go, be illustrative, as if you are talking to someone who has no idea how to begin to do this, because I don't..
thanks.
//------------------check authorization of calendars--------------
#if (__MAC_OS_X_VERSION_MIN_REQUIRED >= 1090) || (__IPHONE_OS_VERSION_MIN_REQUIRED)
if(!eventStore) eventStore = [[EKEventStore alloc] init];
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) //.............put this back in...
{
if (granted)
{
NSLog(#"granted permission to eventstore!");
authorizedEventStore = YES;
authorizedCalendar();
}
else
{
NSLog(#"Not granted");
authorizedEventStore = NO;
notAuthorized();
}
}];
#else
NSLog(#"not able to request");
if(!eventStore) eventStore = [[EKEventStore alloc] initWithAccessToEntityTypes:EKEntityMaskEvent];
authorizedEventStore = YES;
authorizedCalendar();
#endif
//------------------end check authorization of calendars--------------
To have an App that runs on several OS versions:
Set your Base SDK to the latest version of the OS you support, in your case 10.9
Set the Deployment Target to the earliest OS you want your code to launch on
For all calls that don't exist in earlier versions of the OS, you must test before you call, either by using respondsToSelector: (for methods) or testing against nil (for functions and statics). You can if you like do a check for the OS version, but it's more robust to check the specific call.
see also:
How to conditionally use a new Cocoa API and
How do I include calls to methods only present in one operating system version when compiling for multiple versions?
To request access on OS X use:
EKEventStore *eventStore = nil;
if ([EKEventStore respondsToSelector:#selector(authorizationStatusForEntityType:)]) {
// 10.9 style
eventStore = [[EKEventStore alloc] init];
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
{
// your completion
}];
} else {
// 10.8 style
eventStore = [[EKEventStore alloc] initWithAccessToEntityTypes:EKEntityMaskEvent ];
}
I am trying to save a selected email from Apple Mail using ScriptBridge.
I have already created the Mail.h file and in my program I have successfully done other things with the Apple Mail ScriptBridge (like forwarding messages etc.)
Here is my current code. I get no error messages and the code is running fine; only the file never gets created.
I am using Xcode 4.6. on Mountain Lion 10.8.2. The deployment target of my app is 10.8.
- (void)saveEmail {
MailApplication *mailApp = [SBApplication applicationWithBundleIdentifier:#"com.apple.Mail"];
SBElementArray *viewers = [mailApp messageViewers];
for (MailMessageViewer *viewer in viewers) {
NSArray *selectedMessages = [viewer selectedMessages];
#try {
for (MailMessage *selectedMessage in selectedMessages) {
NSString *filePath = [NSString stringWithFormat:#"%#%#",#"/Users/patrick/Documents/",#"tmp.rtf"];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
[selectedMessage saveIn:fileUrl as:MailSaveableFileFormatNativeFormat];
}
}
#catch (NSException *exception) {
NSLog(#"Exception:%#", exception);
}
}
}
Have exactly the same problem. Seems saveIn isn't implemented in Mail.
I have a workaround with this code:
[message.source writeToURL:mailUrl
atomically:YES
encoding:NSUTF8StringEncoding
error:nil];
Where message is an instance of MailMessage
This seems to work correctly most of the time. But sometimes the attachments are empty in the saved mail. So if anyone has a better solution...