Sunday, 24 April 2016

Add actual debug mode in iOS insist of DEBUG macro

You need to check that your app in debug mode or release mode and you edit the scheme, where DEBUG macro will defined by Xcode. But what happen if you change to release mode that time, it is hard to find that app build given by Xcode or archived. Also there is problem with preprocessor macro, if you are writing framework or dynamic lib for iOS, you cannot use preprocessors.

So find a scenario which mean that app is running by the Xcode build (debug) or archived (release), below method would help you. This method is popularly used by hockey app and most famous analytics. [Taken from Hockeyapp SDK]

#include <sys/sysctl.h>
- (BOOL)debug {
    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();
        
        if (sysctl(name, 4, &info, &info_size, NULL, 0) == -1) {
            NSLog(@"App is running in debug mode");
            debuggerIsAttached = false;
        }
        
        if (!debuggerIsAttached && (info.kp_proc.p_flag & P_TRACED) != 0)
            debuggerIsAttached = true;
    });
    return debuggerIsAttached;
}

No comments:

Post a Comment