我有一个旨在在沙盒和非沙盒 MacOS 中运行的应用程序。如果用户从 MacOS 10.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
}
这里是 Swift 4.2 中@hamstergene 的答案:
func isSandboxEnvironment() -> Bool {
let environ = ProcessInfo.processInfo.environment
return (nil != environ["APP_SANDBOX_CONTAINER_ID"])
}