iOS 키체인을 활용해 문자열을 앱의 삭제 이후에도 보존하는 방법이다. 스크립트 하나를 아래와 같이 작성.

using UnityEngine;
using System.Runtime.InteropServices;

public class KeyChain {
	
	#if UNITY_IPHONE || UNITY_STANDALONE_OSX
	
	[DllImport("__Internal")]
	private static extern string getKeyChainUser();
	
	public static string BindGetKeyChainUser()
	{
		return getKeyChainUser();
	}
	
	[DllImport("__Internal")]
	private static extern void setKeyChainUser(string userId);
	
	public static void BindSetKeyChainUser(string userId)
	{
		setKeyChainUser(userId);
	}
	
	[DllImport("__Internal")]
	private static extern void deleteKeyChainUser();
	
	public static void BindDeleteKeyChainUser()
	{
		deleteKeyChainUser();
	}	


  #endif

}

이제 위의 작성한 스크립트의 함수를 받을 Objective-C 파일을 만들 차례.

당연하게 새롭게 만들거나 다운로드한 파일의 위치는 유니티 프로젝트 Plugins/IOS에 위치. (위에 만든 스크립트 위치는 상관없음)


[링크] <- 링크를 통해 아래의 2개 파일을 다운로드.

- UICKeyChainStore.h

- UICKeyChainStore.m



아래의 2개의 파일을 새롭게 생성.

- KeyChainPlugin.h

- KeyChainPlugin.mm


KeyChainPlugin.h의 내용은 아무것도 구현하지 않고 빈 파일로 둠.


KeyChainPlugin.mm의 내용은 아래와 같이 작성.

#import "KeyChainPlugin.h"

#import "UICKeyChainStore.h"

 

NSString *_keyForID = @"UserID";

 

@implementation KeyChainPlugin

 

extern "C" {

    char* getKeyChainUser();

    void setKeyChainUser(const char* userId);

    void deleteKeyChainUser();

}



char* getKeyChainUser()

{

    NSString *userId = [UICKeyChainStore stringForKey:_keyForID];

 

    if (userId == nil || [userId isEqualToString:@""]) {

        NSLog(@"No user information");

userId = @"";

    }

 

NSString* json = [NSString stringWithFormat:@"{\"userId\":\"%@\"}",userId];

 

    return makeStringCopy([json UTF8String]);

}

 

void setKeyChainUser(const char* userId)

{

    NSString *nsUseId = [NSString stringWithCString: userId encoding:NSUTF8StringEncoding];

 

    [UICKeyChainStore setString:nsUseId forKey:_keyForID];

}

 

void deleteKeyChainUser()

{

    [UICKeyChainStore removeItemForKey:_keyForID];

}

 

char* makeStringCopy(const char* str)

{

    if (str == NULL) {

        return NULL;

    }

 

    char* res = (char*)malloc(strlen(str) + 1);

    strcpy(res, str);

    return res;

}

 

@end




전체적인 흐름은 다음과 같음.


1. Keychain.getKeyChainUser() 호출.

2. KeychainPlugin.getKeyChainUser() 진입후, UICKeyChainStore.stringForKey함수를 사용하여 키체인에 접근, UserID의 키에 해당하는 값을 가져옴.

3. 함수를 보면 알겠지만, 값이 null이거나 빈값일 경우 json으로 리턴할 데이터에 값을 따로 지정하지 않음.

4. {"UserID":"ABC"} 형태로 리턴되므로, 유니티에서 해당 값을 반은 후 JSON 데이터를 파싱해서 사용.


* 유니티 API의 SystemInfo.deviceUniqueIdentifier은 호출시 고유한 값을 리턴하지만,  앱을 삭제하고 다시 설치후 호출할 경우 변경된 값을 리턴하므로, 위와 같은 방법을 통해 영구적인 형태로 사용할 수 있음.



참고링크

- http://bribser.co.jp/blog/pluginkeychain/

- http://docs.unity3d.com/kr/current/Manual/PluginsForIOS.html

- https://github.com/kishikawakatsumi/UICKeyChainStore


WRITTEN BY
빨강꼬마

,