샘플 코드
    • PDF

    샘플 코드

    • PDF

    Article Summary

    Classic/VPC 환경에서 이용 가능합니다.

    App Safer 이용에 도움이 되는 다양한 샘플 코드를 확인할 수 있습니다.

    참고

    운영체제별 샘플코드는 다음과 같은 언어로 제공합니다.

    • 안드로이드: Kotlin, Java
    • iOS: Swift, Objective-C

    안드로이드

    안드로이드에서 사용 가능한 샘플 코드를 확인할 수 있습니다.

    SDK

    SDK 연동 방식으로 적용한 App Safer를 실행하는 샘플 코드는 다음과 같습니다.

    Kotlin
    import android.os.Bundle
    import android.util.Log
    import androidx.appcompat.app.AppCompatActivity
    import com.nbp.appsafer.AppSafer
    import java.io.File
    import java.util.*
    
    class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            // Prevent screenshot
            AppSafer.INSTANCE.preventScreenshot(window)
    
            // App Safer start
            if (AppSafer.INSTANCE.start(applicationContext) == 0) {
                // setUserId
                AppSafer.INSTANCE.userId = "ExampleUserId"
    
                // getUserId
                val userId = AppSafer.INSTANCE.userId
                Log.d("AppSafer-UserId", userId)
    
                // getUdid
                val udid = AppSafer.INSTANCE.userDeviceId
                Log.d("AppSafer-UDID", udid)
            }
        }
    }
    
    Java
    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    
    import com.nbp.appsafer.AppSafer;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    
    public class MainActivity extends Activity {
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    
    		// Prevent screenshot
    		AppSafer.INSTANCE.preventScreenshot(getWindow());
    
    		// App Safer start
    		if (AppSafer.INSTANCE.start(getApplicationContext()) == 0) {
    			// setUserId
    			AppSafer.INSTANCE.setUserId("ExampleUserId");
    
    			// getUserId
    			String userId = AppSafer.INSTANCE.getUserId();
    			Log.d("AppSafer-UserId", userId);
    
    			// getUdid
    			String udid = AppSafer.INSTANCE.getUserDeviceId();
    			Log.d("AppSafer-UDID", udid);
    		}
    	}
    }
    

    간편 적용

    간편 적용 방식으로 적용한 App Safer를 실행하는 샘플 코드는 다음과 같습니다.

    Kotlin
    import android.app.Activity
    import android.os.Bundle
    import com.nbp.appsafer.AppSafer
    
    class MainActivity : Activity() {
        private fun getAppSaferInstance(): Any? {
            var appSaferInstance: Any? = null
            try {
                val clazz = Class.forName("com.nbp.appsafer.AppSafer")
                val enumConstants = clazz.enumConstants
                if ("INSTANCE" == enumConstants[0].toString()) {
                    appSaferInstance = enumConstants[0]
                }
            } catch (ignored: Exception) {
                // ClassNotFoundException
                // IllegalAccessException
            }
            return appSaferInstance
        }
    
        private fun getUserId(): String? {
            var userId: String? = null
            try {
                val appSaferInstance = getAppSaferInstance()
                userId = appSaferInstance?.javaClass?.getDeclaredMethod("getUserId")
                    ?.invoke(appSaferInstance) as String?
            } catch (ignored: Exception) {
                // NoSuchMethodException
                // InvocationTargetException
            }
            return userId
        }
    
        private fun setUserId(userId: String) {
            try {
                val appSaferInstance = getAppSaferInstance()
                appSaferInstance?.javaClass?.getDeclaredMethod("setUserId", String::class.java)
                    ?.invoke(appSaferInstance, userId)
            } catch (ignored: Exception) {
                // NoSuchMethodException
                // InvocationTargetException
            }
        }
    
        private fun getUserDeviceId(): String? {
            var udid: String? = null
            try {
                val appSaferInstance = getAppSaferInstance()
                udid = appSaferInstance?.javaClass?.getDeclaredMethod("getUserDeviceId")
                    ?.invoke(appSaferInstance) as String?
            } catch (ignored: Exception) {
                // NoSuchMethodException
                // InvocationTargetException
            }
            return udid
        }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            // setUserId
            setUserId("ExampleUserId")
    
            // getUserId
            val userId = getUserId()
    
            // getUdid
            val udid = getUserDeviceId()
        }
    }
    
    Java
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    
    public class MainActivity extends Activity {
    	private Object getAppSaferInstance() {
    		Object appSaferInstance = null;
    
    		try {
    			Class<?> clazz = Class.forName("com.nbp.appsafer.AppSafer");
    			Object[] enumConstants = clazz.getEnumConstants();
    			if ("INSTANCE".equals(enumConstants[0].toString())) {
    				appSaferInstance = enumConstants[0];
    			}
    		} catch (Exception ignored) {
    			// ClassNotFoundException
    			// IllegalAccessException
    		}
    
    		return appSaferInstance;
    	}
    
    	private String getUserId() {
    		String userId = null;
    
    		try {
    			Object appSaferInstance = getAppSaferInstance();
    			userId = (String)appSaferInstance.getClass().getDeclaredMethod("getUserId").invoke(appSaferInstance);
    		} catch (Exception ignored) {
    			// NoSuchMethodException
    			// InvocationTargetException
    		}
    
    		return userId;
    	}
    
    	private void setUserId(String userId) {
    		try {
    			Object appSaferInstance = getAppSaferInstance();
    			appSaferInstance.getClass().getDeclaredMethod("setUserId", String.class).invoke(appSaferInstance, userId);
    		} catch (Exception ignored) {
    			// NoSuchMethodException
    			// InvocationTargetException
    		}
    	}
    
    	private String getUserDeviceId() {
    		String udid = null;
    
    		try {
    			Object appSaferInstance = getAppSaferInstance();
    			udid = (String)appSaferInstance.getClass().getDeclaredMethod("getUserDeviceId").invoke(appSaferInstance);
    		} catch (Exception ignored) {
    			// NoSuchMethodException
    			// InvocationTargetException
    		}
    
    		return udid;
    	}
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    		// setUserId
    		setUserId("ExampleUserId");
    
    		// getUserId
    		String userId = getUserId();
    
    		// getUdid
    		String udid = getUserDeviceId();
        }
    }
    

    iOS

    iOS에서 사용 가능한 샘플 코드를 확인해 주십시오.

    초기화

    초기화를 위한 샘플 코드는 다음과 같습니다.

    Swift
    import SwiftUI
    
    struct ContentView: View {
        func initAppSaferExample() {
            // APP_SAFER_KEY generated when registering an app to the Console
            let result = AppSafer().initAppSafer(AppSaferDelegator.delegator, serviceCode: "ncloud", key: "<APP_SAFER_KEY>")
    
            NSLog("initAppSafer() result: %d", result);
    
            if(result == SUCCESS) {
                // init success
            } else if(result == FAIL) {
                // init fail
            }
        }
    
        var body: some View {
            Button("initAppSafer") {
                initAppSaferExample()
            }
        }
    }
    
    class AppSaferDelegator: NSObject, AppSaferDelegate {
        static let delegator = AppSaferDelegator()
        private override init() {}
        
        func appSaferDidInitFinish(_ result: Int32) {
            print("appSaferDidInitFinish result \(result)");
            if(result == BLOCK) {
                print("Device is blocked!");
                // add to exit application logic
            }
        }
    }
    
    Objective-C
    #import <AppSaferFramework/AppSaferFramework.h>
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        AppSafer *appSafer = [[AppSafer alloc] init];
    
        int res = FAIL;
        if(appSafer != nil) {
            // APP_SAFER_KEY generated when registering an app to the Console
            res = [appSafer initAppSafer:self serviceCode:@"ncloud" key:"<APP_SAFER_KEY>"];
            
            NSLog(@"initAppSafer result %d", res);
    
            if(res == SUCCESS) {
                // init success
            } else if(res == FAIL) {
                // init fail
            }
        } else {
            NSLog(@"AppSafer is nil");
        }
    }
    
    - (void)appSaferDidInitFinish:(NSUInteger)result msg:(NSString *)message {
        NSLog(@"appSaferDidInitFinish result %d", result);
        if(result == BLOCK) {
            NSLog(@"Device is blocked!");
            // add to exit application logic
        }
    }
    

    실시간 보안 탐지

    실시간 보안 탐지를 실행하는 샘플 코드는 다음과 같습니다.

    Swift
    import SwiftUI
    
    struct ContentView: View {
        func checkTamperingExample() {
            let result = AppSafer().checkTampering()
            
            switch(result) {
            case FAIL:
                print("Failed to check tampering")
                break
            case SUCCESS:
                print("Check Tampering Success")
                break
            case BLOCK:
                print("Device is blocked")
                break
            case BEFOREINIT:
                print("AppSafer is not initialized")
                break
            default:
                break
            }
        }
    
        var body: some View {
            Button("checkTampering") {
                checkTamperingExample()
            }
        }
    }
    
    class AppSaferDelegator: NSObject, AppSaferDelegate {
        static let delegator = AppSaferDelegator()
        private override init() {}
        
        func appSaferDidCheckTamperingFinish(_ result: Int32) {
            print("appSaferDidCheckTamperingFinish result: " + (
                  result == FAIL   ? "FAIL" :
                  result == SAFE   ? "SAFE" :
                  result == DETECT ? "DETECT" :
                  result == BLOCK  ? "BLOCK": "UNKNOWN"))
    
            if(result == BLOCK) {
                print("Device is blocked!")
                // add to exit application logic
            }
        }
    
        func appSaferDetectedJailbreak() {
            print("[DETECT] appSaferDetectedJailbreak");
        }
        
        func appSaferDetectedSimulator() {
            print("[DETECT] appSaferDetectedSimulator");
        }
    
        func appSaferDetectedDebugging() {
            print("[DETECT] appSaferDetectedDebugging");
        }
        
        func appSaferDetectedMemoryTampered() {
            print("[DETECT] appSaferDetectedMemoryTampered");
        }
    }
    
    Objective-C
    @implementation ViewController
    
    - (IBAction)checkAppSafer:(id)sender {
        AppSafer *appSafer = [[AppSafer alloc] init];
        
        if(appSafer != nil) {
            int res = [appSafer checkTampering];
            
            switch(res) {
                case FAIL:
                    NSLog(@"Failed to check tampering");
                    break;
                case SUCCESS:
                    NSLog(@"Check Tampering Success");
                    break;
                case BLOCK:
                    NSLog(@"Device is blocked");
                    break;
                case BEFOREINIT:
                    NSLog(@"AppSafer is not initialized");
                    break;
            }
        } else {
            NSLog(@"AppSafer is nil");
        }
    }
    
    - (void)appSaferDidCheckTamperingFinish:(int)result {
        if(result == BLOCK) {
            [self.msgbox setText:@"Device is blocked!"];
            // add to exit application
        }
    
        NSLog(@"appSaferDidCheckTamperingFinish result %@",
              result == FAIL   ? @"FAIL" :
              result == SAFE   ? @"SAFE" :
              result == DETECT ? @"DETECT" :
              result == BLOCK  ? @"BLOCK": @"UNKNOWN");
    }
    
    - (void)appSaferDetectedJailbreak {
        NSLog(@"[DETECT] appSaferDetectedJailbreak");
    }
    
    - (void)appSaferDetectedSimulator {
        NSLog(@"[DETECT] appSaferDetectedSimulator");
    }
    
    - (void)appSaferDetectedDebugging {
        NSLog(@"[DETECT] appSaferDetectedDebugging");
    }
    
    - (void)appSaferDetectedMemoryTampered {
        NSLog(@"[DETECT] appSaferDetectedMemoryTampered");
    }
    

    이 문서가 도움이 되었습니까?

    Changing your password will log you out immediately. Use the new password to log back in.
    First name must have atleast 2 characters. Numbers and special characters are not allowed.
    Last name must have atleast 1 characters. Numbers and special characters are not allowed.
    Enter a valid email
    Enter a valid password
    Your profile has been successfully updated.