iOS - 检测应用程序是否正在从 Xcode 运行

标签 ios xcode debugging preprocessor

<分区>

我正在尝试根据代码是通过 USB/Xcode(调试)运行还是在从应用商店下载的生产模式(发布)运行,来启用/禁用部分代码。我知道检查它是否在 DEBUGRELEASE 模式下运行,如下所示:

enter image description here

#ifdef DEBUG

// Stuff for debug mode

#else

// Stuff for release mode

#endif

但问题是,我发现一个明显的漏洞是您可以将“运行”构建方案的构建配置从“调试”更改为“发布”。更好的方法是,如果我可以简单地检测它是否从 Xcode 运行。我还没有找到检查这一点的方法。

有没有办法检查 iOS 应用程序是否正在从 Xcode 运行?

最佳答案

您可以使用 sysctl 检查是否附加了调试器(可能但不一定是 Xcode)。方法如下 HockeyApp does it :

#include <Foundation/Foundation.h>
#include <sys/sysctl.h>

/**
 * Check if the debugger is attached
 *
 * Taken from https://github.com/plausiblelabs/plcrashreporter/blob/2dd862ce049e6f43feb355308dfc710f3af54c4d/Source/Crash%20Demo/main.m#L96
 *
 * @return `YES` if the debugger is attached to the current process, `NO` otherwise
 */
- (BOOL)isDebuggerAttached {
  static BOOL debuggerIsAttached = NO;

  static dispatch_once_t debuggerPredicate;
  dispatch_once(&debuggerPredicate, ^{
    struct kinfo_proc info;
    size_t info_size = sizeof(info);
    int name[4];

    name[0] = CTL_KERN;
    name[1] = KERN_PROC;
    name[2] = KERN_PROC_PID;
    name[3] = getpid(); // from unistd.h, included by Foundation

    if (sysctl(name, 4, &info, &info_size, NULL, 0) == -1) {
      NSLog(@"[HockeySDK] ERROR: Checking for a running debugger via sysctl() failed: %s", strerror(errno));
      debuggerIsAttached = false;
    }

    if (!debuggerIsAttached && (info.kp_proc.p_flag & P_TRACED) != 0)
      debuggerIsAttached = true;
  });

  return debuggerIsAttached;
}

关于iOS - 检测应用程序是否正在从 Xcode 运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27252898/

相关文章:

ios - XCode 创建一个 Button Toggle,显示一张图像用于 On 和一张用于 Off 功能

ios - 无法在 iOS 项目中使用库,该库在具有相同设置的另一个项目中工作

git - git add 的详细显示

javascript - 为什么在使用 reactjs Hook 时会出现 "TypeError: react__WEBPACK_IMPORTED_MODULE_1___default.a.useState is not a function"错误?

ios - UITextField 移动时出错

ios - 检索数据后 Collection View 未重新加载

ios - 应用程序中的状态栏消失了(Xcode iphone)

ios - 如何根据IOS中的时间更改十六进制颜色代码

c - 使用 GoogleTest 访问项目中包含的 jpg 文件的最佳方式是什么?

php - PHP解析/语法错误;以及如何解决它们