使用Mac OSX SDK,我编写了这个简单的测试应用程序,用于从正在运行的应用程序中提取版本字符串。
int main()
{
NSWorkspace * ws = [NSWorkspace sharedWorkspace];
NSArray * apps = [ws runningApplications];
NSUInteger max= [apps count];
for (NSUInteger i = 0; i < max; i++)
{
NSRunningApplication *app = [apps objectAtIndex: i];
pid_t pid = [ app processIdentifier ];
ProcessSerialNumber psn = { kNoProcess, kNoProcess };
if ( GetProcessForPID(pid, &psn) != noErr )
continue;
CFDictionaryRef dictionary
= ProcessInformationCopyDictionary(&psn, kProcessDictionaryIncludeAllInformationMask);
const NSString * version
= reinterpret_cast<const NSString*>(CFDictionaryGetValue( dictionary, CFSTR("CFBundleShortVersionString") ));
printf( "version for pid %d: \"%s\"\n", pid, [ version UTF8String ] );
}
}
但这不起作用,它会打印如下行:
pid 34的版本:“(null)”
第二次尝试
如果我通过将最后两行改为:{/ p>来尝试检索CFBundleVersion
,我会更接近
const NSNumber * version
= reinterpret_cast<const NSNumber *>(CFDictionaryGetValue( dictionary, CFSTR("CFBundleVersion") ));
printf( "version for pid %d: \"%s\"\n", pid, [ [ version stringValue ] UTF8String ] );
但现在版本是一个整数,如257633863,我想要像1.23.0
答案 0 :(得分:1)
阅读包的Info.plist
词典可能更容易:
NSWorkspace *ws = [NSWorkspace sharedWorkspace];
NSArray *apps = [ws runningApplications];
for (NSRunningApplication *app in apps)
{
pid_t pid = [app processIdentifier ];
NSBundle *bundle = [NSBundle bundleWithURL:[app bundleURL]];
NSDictionary *info = [bundle infoDictionary];
NSString *name = info[@"CFBundleName"];
NSString *identifier = info[@"CFBundleIdentifier"];
NSString *version = info[@"CFBundleVersion"];
NSString *shortVersion = info[@"CFBundleShortVersionString"];
NSLog(@"PID: %ld, Name: %@, Identifier: %@, Version: %@ (%@)", (long)pid, name, identifier, version, shortVersion);
}
答案 1 :(得分:1)
您可以使用此类方法检查特定的应用版本。
+(BOOL) isCorrectApp:(NSString*) appIdentifier forVersion: (NSString*) appVersion {
NSWorkspace *ws = [NSWorkspace sharedWorkspace];
NSArray *apps = [ws runningApplications];
for (NSRunningApplication *app in apps)
{
NSBundle *bundle = [NSBundle bundleWithURL:[app bundleURL]];
NSDictionary *info = [bundle infoDictionary];
NSString *identifier = info[@"CFBundleIdentifier"];
if ([identifier containsString:appIdentifier]) { // appIdentifier is com.apple.iTunesHelper or such
NSString *name = info[@"CFBundleName"];
NSString *version = info[@"CFBundleVersion"];
NSString *shortVersion = info[@"CFBundleShortVersionString"];
if ([version hasPrefix:appVersion]) {
NSLog(@"Name: %@, Identifier: %@, Version: %@ (%@)", name, identifier, version, shortVersion);
} else {
// NSLog(@"Waiting for the right version.");
return false;
}
}
}
return true;
}
在使用商业软件之前,请务必先测试一下。