iOS Keychain Documentation

Overview

Welcome to the iOS Keychain documentation page. iOS Keychain allows access to the iOS keychain on mobile devices inside of Unity.

Setting up the Plugin

The only required framework for iOS Keychain to work is Security.framework. Include this automatically in your builds if it isn't already by selecting the KeyChainPlugin.mm file in your project and in the inspector check the Security checkbox under Framework dependencies and hit Apply.

Using iOS Keychain

Storing a value using the plugin is very simple. You can only store one key and value for the application so you must combine any data you want to store into a concatenated or serialized string (JSON works best). The maximum length for the key and value is appoximately 4 billion characters so you shouldn't have any issues fitting your data. Here is a simple example using commas to seperate player data.

Note: The default seperator character used by the plugin is the pipe character "|". DO NOT use this to seperate your data.

Set user data:

string playerName = "Player1234";
int playerHealth = 123;
string combinedData = playerName + "," + playerHealth;
KeyChainBinding.SetKeyChainData("mygame", combinedData);

Get user data:

// get the data from the keychain
string key, data;
KeyChainBinding.GetKeyChainData(out key, out data);

// repopulate the player data
string[] split = data.Split(',');
string playerName = split[0];
int playerHealth = int.Parse(split[1]);

JSON Example

A more efficient and easier method would be to use JSON and convert a player data class. Here's an short example below.

public class PlayerGameData
{
	public string playerName { get; set; }
	public int playerLevel { get; set; }
	public int[] completedLevels { get; set; }
	public string[] purchasedItems { get; set; }
	
	public PlayerGameData()
	{
		completedLevels = new int[0];
		purchasedItems = new string[0];
	}	
	public static void SaveData(PlayerGameData gameData)
	{
		string serializedData = JsonConvert.SerializeObject(gameData);
		KeyChainBinding.SetKeyChainData("mygame", serializedData);
	}
	public static PlayerGameData LoadSave()
	{
		// get the data from the keychain
		string key, data;
		KeyChainBinding.GetKeyChainData(out key, out data);
		
		// if the key is null or empty, no data has yet been saved
		if (string.IsNullOrEmpty(key))
			return new PlayerGameData();
		return (PlayerGameData)JsonConvert.DeserializeObject(data);
	}
}

// Then you can simply call LoadSave() and SaveData() from anywhere in your application
PlayerGameData myPlayerData = PlayerGameData.LoadSave();
PlayerGameData.SaveData(myPlayerData);

If you have any questions or issues please email me at jschieck@gmail.com and thanks for your support!