我有一个应用程序,它的目标是在沙盒和非沙盒的MacOS中运行。如果用户从MacOS10.6升级到更高版本的操作系统,我需要用户重新选择文件夹,这样我就可以用安全的书签为它们添加书签。
如何检测我的应用程序位于支持沙盒的操作系统上?
我所知道的唯一方法是查找APP_SANDBOX_CONTAINER_ID
环境变量。当应用程序在沙盒容器中运行时,它就会出现。
NSDictionary* environ = [[NSProcessInfo processInfo] environment];
BOOL inSandbox = (nil != [environ objectForKey:@"APP_SANDBOX_CONTAINER_ID"]);
BOOL isSandboxed = NO;
SecStaticCodeRef staticCode = NULL;
NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
if (SecStaticCodeCreateWithPath((__bridge CFURLRef)bundleURL, kSecCSDefaultFlags, &staticCode) == errSecSuccess) {
if (SecStaticCodeCheckValidityWithErrors(staticCode, kSecCSBasicValidateOnly, NULL, NULL) == errSecSuccess) {
SecRequirementRef sandboxRequirement;
if (SecRequirementCreateWithString(CFSTR("entitlement["com.apple.security.app-sandbox"] exists"), kSecCSDefaultFlags,
&sandboxRequirement) == errSecSuccess)
{
OSStatus codeCheckResult = SecStaticCodeCheckValidityWithErrors(staticCode, kSecCSBasicValidateOnly, sandboxRequirement, NULL);
if (codeCheckResult == errSecSuccess) {
isSandboxed = YES;
}
}
}
CFRelease(staticCode);
}
Swift3 测试
func isSandboxed() -> Bool {
let bundleURL = Bundle.main.bundleURL
var staticCode:SecStaticCode?
var isSandboxed:Bool = false
let kSecCSDefaultFlags:SecCSFlags = SecCSFlags(rawValue: SecCSFlags.RawValue(0))
if SecStaticCodeCreateWithPath(bundleURL as CFURL, kSecCSDefaultFlags, &staticCode) == errSecSuccess {
if SecStaticCodeCheckValidityWithErrors(staticCode!, SecCSFlags(rawValue: kSecCSBasicValidateOnly), nil, nil) == errSecSuccess {
let appSandbox = "entitlement["com.apple.security.app-sandbox"] exists"
var sandboxRequirement:SecRequirement?
if SecRequirementCreateWithString(appSandbox as CFString, kSecCSDefaultFlags, &sandboxRequirement) == errSecSuccess {
let codeCheckResult:OSStatus = SecStaticCodeCheckValidityWithErrors(staticCode!, SecCSFlags(rawValue: kSecCSBasicValidateOnly), sandboxRequirement, nil)
if (codeCheckResult == errSecSuccess) {
isSandboxed = true
}
}
}
}
return isSandboxed
}
这里是@hamstergene在Swift 4.2中的答案:
func isSandboxEnvironment() -> Bool {
let environ = ProcessInfo.processInfo.environment
return (nil != environ["APP_SANDBOX_CONTAINER_ID"])
}