Get OSX version with objective-c - objective-c

How would I be able to get the OSX version in objective-c? I would like to avoid using shell commands. E.g "10.5" or "10.4"

NSProcessInfo *pInfo = [NSProcessInfo processInfo];
NSString *version = [pInfo operatingSystemVersionString];
Sorry for the formatting, I'm using my iPad to answer this.

As of 10.10 you can use NSProcessInfo.processInfo.operatingSystemVersion to get a NSOperatingSystemVersion struct.
typedef struct {
NSInteger majorVersion;
NSInteger minorVersion;
NSInteger patchVersion;
} NSOperatingSystemVersion;
There's also a helpful isOperatingSystemAtLeastVersion: method.
NSOperatingSystemVersion minimumSupportedOSVersion = { .majorVersion = 10, .minorVersion = 12, .patchVersion = 0 };
BOOL isSupported = [NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:minimumSupportedOSVersion];

You can parse it in this way to get the format you want:
NSProcessInfo *pinfo = [NSProcessInfo processInfo];
NSArray *myarr = [[pinfo operatingSystemVersionString] componentsSeparatedByString:#" "];
NSString *version = [#"Mac OS X " stringByAppendingString:[myarr objectAtIndex:1]];
This f.e. will give you Mac OS X 10.6.8

You can use the Gestalt function to access the components of the OS version.
Old-time users of Gestalt may be amazed to find that it is still available in 64-bit.

See this response using NSAppKitVersionNumber in case you're using AppKit in your app as well (and want to run on 10.8+ as Gestalt is now deprecated):
How to know what Mac OS the app is running on?

add this code after #import
#define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
after adding above code please add below code where you want to see your os-version
NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
NSLog(#"System version :%#",systemVersion);
you can easily get OS-version by above code
Thank you

Related

Fixing "Use of undeclared identifier 'NSPreferencePanesDirectory'"

My application uses the following code:
#if MAC_OS_X_VERSION_10_5 < MAC_OS_X_VERSION_MAX_ALLOWED
NSArray *globalPreferencePanes =
NSSearchPathForDirectoriesInDomains(NSPreferencePanesDirectory,
NSAllDomainsMask, YES);
#else
NSArray *globalPreferencePanes =
[NSArray arrayWithObjects:#"/Library/PreferencePanes",
[#"~/Library/PreferencePanes" stringByExpandingTildeInPath], nil];
#endif
return globalPreferencePanes;
The project under which I'm compiling this is aimed at the 10.5 Mac OSX SDK, where NSPreferencePanesDirectory does not exist (it only exists in 10.6+). Because of this, I have the #if and #else in order to check what version of Mac OSX we're running under, so I know whether I should use the NSPreferencePanesDirectory or just manually give the location of the preference pane directories.
What should I change in order to stop getting this "use of undeclared identifier" error?
Thanks.
#if is evaluated at compile time, not run time. What you probably want to do is use the current SDK (10.7), and do something like this:
NSArray *globalPreferencePanes;
if (NSAppKitVersionNumber >= NSAppKitVersionNumber10_6)
globalPreferencePanes = NSSearchPathForDirectoriesInDomains(NSPreferencePanesDirectory, NSAllDomainsMask, YES);
else
globalPreferencePanes = [NSArray arrayWithObjects:#"/Library/PreferencePanes", [#"~/Library/PreferencePanes" stringByExpandingTildeInPath], nil];
return globalPreferencePanes;
Making sure to set your target OS version to 10.5 so the symbol is weak linked. Otherwise, you could drop down and use CoreServices' FSFindFolder():
NSMutableArray *globalPreferencePanes = [NSMutableArray array];
FSRef foundRef;
OSErr err = FSFindFolder(kLocalDomain, kPreferencePanesFolderType, false, &foundRef);
if (err != noErr) {
CFURLRef url = CFURLCreateFromFSRef(NULL, &fsRef);
CFStringRef path = CFURLCopyPath(url);
[globalPreferencePanes addObject:(id)path];
CFRelease(path);
CFRelease(url);
}
OSErr err = FSFindFolder(kUserDomain, kPreferencePanesFolderType, false, &foundRef);
if (err != noErr) {
CFURLRef url = CFURLCreateFromFSRef(NULL, &fsRef);
CFStringRef path = CFURLCopyPath(url);
[globalPreferencePanes addObject:(id)path];
CFRelease(path);
CFRelease(url);
}
return globalPreferencePanes;
(Not tested)
If you are using 10.5.x you will still get an error since "NSPreferencePanesDirectory" is not a known symbol. I solved this issue for a friend and changed the FindPrefsDir function code in osxsupport.m to:
char *FindPrefsDir(void)
{
char *resstr = NULL;
NSArray *globalPreferencePanes;
globalPreferencePanes = [NSArray arrayWithObjects:#"/Library/PreferencePanes", [#"~/Library/PreferencePanes" stringByExpandingTildeInPath], nil];
if ([globalPreferencePanes count] > 0)
{
resstr = StringToChar([globalPreferencePanes objectAtIndex:0]) ;
}
return resstr;
}
Thanks to Wevah for his code suggestion, but it didn't directly work for me. So I changed it a little bit and my friend who is still on 10.5.x could perfectly build it after that.

Find Mac OS X version number in objective c

How can I find the version number of Mac OS X (eg. "10.6.7") from my Cocoa Objective-C application?
#import <CoreServices/CoreServices.h>
SInt32 major, minor, bugfix;
Gestalt(gestaltSystemVersionMajor, &major);
Gestalt(gestaltSystemVersionMinor, &minor);
Gestalt(gestaltSystemVersionBugFix, &bugfix);
NSString *systemVersion = [NSString stringWithFormat:#"%d.%d.%d",
major, minor, bugfix];
You could use the same technique that Apple's code uses...
NSDictionary *systemVersionDictionary =
[NSDictionary dictionaryWithContentsOfFile:
#"/System/Library/CoreServices/SystemVersion.plist"];
NSString *systemVersion =
[systemVersionDictionary objectForKey:#"ProductVersion"];
Apple does exactly this to fill in the version number for various system utilities in the function _CFCopySystemVersionDictionary here:
http://opensource.apple.com/source/CF/CF-744/CFUtilities.c
For OS X 10.10+ I think using NSProcessInfo is an easier and safer way to do that:
NSOperatingSystemVersion version = [[NSProcessInfo processInfo] operatingSystemVersion];
NSLog([NSString stringWithFormat:#"%ld.%ld.%ld", version.majorVersion, version.minorVersion, version.patchVersion]);

Checking if UIGraphicsBeginImageContextWithOptions is supported

I'm working on an iOS app. It currently only works on iOS 4 since I use the following method on several occasions: "UIGraphicsBeginImageContextWithOptions". This method is only available in iOS 4 and therefor my app currently crashes/doesn't work on iPhone OS 3. Aside from this method there is no reason why the app should not work on iPhone OS 3. How do I make a check to see wether or not this method is available ? I've tried the following without succes:
if([self respondsToSelector:#selector(UIGraphicsBeginImageContextWithOptions)]) {
UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0.0); // this will crop
}
else
{
UIGraphicsBeginImageContext(targetSize);
}
I've only tried variations like this:
if([self respondsToSelector:#selector(UIGraphicsBeginImageContextWithOptions:size:opaque:scale:)])
and
if([self respondsToSelector:#selector(UIGraphicsBeginImageContextWithOptions:)])
Without succes. Any help would be appreciated.
UIGraphicsBeginImageContextWithOptions is a C function, so you can't use Objective-C methods like -respondsToSelector: to test its existence.
You could, however, weak link the UIKit framework, and then check if UIGraphicsBeginImageContextWithOptions is NULL:
if (UIGraphicsBeginImageContextWithOptions != NULL) {
UIGraphicsBeginImageContextWithOptions(...);
} else {
UIGraphicsBeginImageContext(...);
}
I have the same problem. You could try testing the system version. This seems to work for me on the devices I tested.
char majorVersion = [[[UIDevice currentDevice] systemVersion] characterAtIndex: 0];
if (majorVersion == '2' || majorVersion == '3')
UIGraphicsBeginImageContext(...);
else
UIGraphicsBeginImageContextWithOptions(...);
I know this is an old question, but with new Xcode and iOS versions (upper than 9) any of this methods work for me.
I always check the system version in this way:
NSString *sysver = [[UIDevice currentDevice] systemVersion];
NSArray *versionNums = [sysver componentsSeparatedByString:#"."];
int majorVersion = [versionNums[0] intValue];
if (majorVersion > 3){
UIGraphicsBeginImageContextWithOptions(...);
}
else{
UIGraphicsBeginImageContext(...);
}
I hope this could help anyone.

How to get and set the wallpaper in objective c on Mac OSX?

I am looking for a way to get (and set) the wallpaper in objective c under Mac OS X.
Do you have code/pointer for this?
Thanks in advance for your help.
For OSX >= 10.6 use NSWorkSpace:
-desktopImageURLForScreen:
-setDesktopImageURL:forScreen:options:error:
For a CFPreferences-based solution see e.g. the topdraw sources:
CFStringRef appID = CFSTR("com.apple.desktop");
CFStringRef bkg = CFSTR("Background");
// get:
NSDictionary *origBackgroundDict = (NSDictionary)CFPreferencesCopyAppValue(bkg, appID);
// ...
// set and notify dock:
CFPreferencesSetAppValue(bkg, (CFPropertyListRef)backgroundDict, appID);
CFPreferencesAppSynchronize(appID);
[[NSDistributedNotificationCenter defaultCenter]
postNotificationName:#"com.apple.desktop" object:#"BackgroundChanged"];

What is the simplest implementation of Markdown for a Cocoa application?

I'm writing a Cocoa application in Objective-C, and I would like to be able to incorporate Markdown. The user will enter text in Markdown syntax, click an "export" button, and the program will output a file of XHTML.
It seems like there are a lot of options, though. I could use one of the C/C++ implementations, I could run the Perl script as a resource to my Cocoa app, I assume could use the Python implementation and the PyObjC bridge or the Perl implementation and the CamelBones or PerlObjC bridges. What would be the simplest and easiest solution? I'm not doing anything complicated like a real-time rendered preview that would require threading.
I had a look at the various options, and in the end found libsoldout, a very small C implementation that's quite easy to integrate. You just need to include array.[ch], buffer.[ch], markdown.[ch], and renderers.[ch] in your Xcode project, then you can convert an NSString from markdown to HTML like so:
NSString *rawMarkdown;
const char * prose = [rawMarkdown UTF8String];
struct buf *ib, *ob;
int length = rawMarkdown.length + 1;
ib = bufnew(length);
bufgrow(ib, length);
memcpy(ib->data, prose, length);
ib->size = length;
ob = bufnew(64);
markdown(ob, ib, &mkd_xhtml);
NSString *shinyNewHTML = [NSString stringWithUTF8String: ob->data];
NSLog(#"%#", shinyNewHTML);
bufrelease(ib);
bufrelease(ob);
I just used the Sundown implementation which includes SmartyPants support, in an iPad app with great success. Took about 15 minutes to build a test app.
Assume you have a UITextView *textView (which you setDelegate:self) and also a UIWebView *webView in which to display the results:
- (void) textViewDidEndEditing:(UITextView *)textView
{
NSString *rawMarkdown = [textView text];
const char * prose = [rawMarkdown UTF8String];
struct buf *ib, *ob;
int length = [rawMarkdown lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
ib = bufnew(length);
bufgrow(ib, length);
memcpy(ib->data, prose, length);
ib->size = length;
ob = bufnew(64);
struct sd_callbacks callbacks;
struct html_renderopt options;
struct sd_markdown *markdown;
sdhtml_renderer(&callbacks, &options, 0);
markdown = sd_markdown_new(0, 16, &callbacks, &options);
sd_markdown_render(ob, ib->data, ib->size, markdown);
sd_markdown_free(markdown);
NSString *shinyNewHTML = [NSString stringWithUTF8String: ob->data];
[webView loadHTMLString:shinyNewHTML baseURL:[[NSURL alloc] initWithString:#""]];
bufrelease(ib);
bufrelease(ob);
}
You may want to check out the open-source app Macdown which I wrote (or alternatively rentzsch's Markdownlive), which incorporate this functionality as the sole purpose of the two apps.
I found problems with processing large amounts of markdown with these C-based libraries.
There's a very simple Obj-C library that worked for me here:
https://github.com/mdiep/MMMarkdown
Steps to use MMMarkdown:
Build the OS X or iOS target
Copy include/MMMarkdown.h and either
lib/libMMMarkdown-Mac.a or lib/libMMMarkdown-iOS.a into your project
Then the code is:
#import "MMMarkdown.h"
NSError *error;
NSString *markdown = #"# Example\nWhat a library!";
NSString *htmlString = [MMMarkdown HTMLStringWithMarkdown:markdown error:&error];
// Returns #"<h1>Example</h1>\n<p>What a library!</p>"
I've used peg-markdown, it's much faster than the original perl and can handle a few syntax extensions if you enable them.
Oliver Letterer's GHMarkdownParser translate markdown to HTML.
Phil Toland's QLMarkdown QuickLook generator for markdown files.