Sample code
    • PDF

    Sample code

    • PDF

    Article Summary

    Available in Classic and VPC

    You can find various sample codes to help you use App Safer.

    Note

    Sample codes for each operating systems are provided in the following languages.

    • Android: Kotlin, Java
    • iOS: Swift, Objective-C

    Android

    You can find sample codes available in Android.

    SDK

    The sample code that runs App Safer applied with the SDK connection method is as follows:

    Kotlin```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)
        }
    }
    

    }

    
    </details>
    <details>
    <summary>Java</summary>
    ```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);
    		}
    	}
    }
    

    Simple application

    The sample code that runs App Safer applied with the simple application method is as follows.

    Kotlin```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()
    }
    

    }

    
    </details>
    <details>
    <summary>Java</summary>
    ```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

    Please check sample codes available in iOS.

    Reset

    The sample code for reset is as follows:

    Swift```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
        }
    }
    

    }

    
    </details>
    <details>
    <summary>Objective-C</summary>
    ```objc
    #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
        }
    }
    

    Real-time Security detection

    The sample code that runs real-time security detection is as follows:

    Swift```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");
    }
    

    }

    
    </details>
    <details>
    <summary>Objective-C</summary>
    ```objc
    @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");
    }
    

    Was this article helpful?

    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.