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

Kev*_*_TA 11 debugging xcode preprocessor ios

我试图根据代码是通过USB/Xcode(调试)运行,还是从app store(发布版)下载的生产模式启用/禁用部分代码.我知道检查它是否正在运行DEBUGRELEASE模式如下:

在此输入图像描述

#ifdef DEBUG

// Stuff for debug mode

#else

// Stuff for release mode

#endif
Run Code Online (Sandbox Code Playgroud)

但问题是,我看到一个明显的循环漏洞,你可以将'Run'构建方案的Build Configuration从'Debug'更改为'Release'.更好的方法是,如果我可以简单地检测它是否从Xcode运行.我还没有办法检查这个.

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

Ste*_*her 18

您可以检查是否附加了调试器(可能,但不一定是Xcode)sysctl.这是HockeyApp如何做到的:

#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;
}
Run Code Online (Sandbox Code Playgroud)