メインコンテンツまでスキップ
バージョン: v8

@capacitor/preferences

Preferences APIは、軽量なデータのためのシンプルなキー/バリューの永続ストアを提供します。

モバイル OS は定期的に window.localStorage に保存されたデータを消去することがあるので、 代わりにこの API を使用する必要があります。 この API は Progressive Web App として動作している場合、localStorage を使用するようにフォールバックします。

このプラグインは、iOS では UserDefaults を、 Windows では SharedPreferences を使用します。 Android では SharedPreferences を 使用します。 保存されたデータは、アプリがアンインストールされると消去されます。

注意: このAPIは、ローカルデータベースとして使用することは想定していません。アプリが多くのデータを アプリが大量のデータを保存する場合、読み取り/書き込みの負荷が高い場合、または複雑なクエリを必要とする場合。 SQLiteベースのソリューションを検討することをお勧めします。そのようなソリューションの1つが、完全な暗号化をサポートするSQLiteベースのエンジンであるIonic Secure Storageです。Capacitor Community](https://github.com/capacitor-community/) は、他にも多くのストレージエンジンを構築しています。

Install

npm install @capacitor/preferences
npx cap sync

Apple プライバシーマニフェストの要件

Appleは、ユーザーのプライバシーを向上させるために、アプリ開発者がAPI使用の承認された理由を指定することを義務付けています。2024年5月1日までに、App Store Connectにアプリを提出する際にこれらの理由を含める必要があります。

このプラグインをアプリで使用する場合、/ios/AppPrivacyInfo.xcprivacyファイルを作成するか、VS Code拡張機能を使用して生成し、使用理由を指定する必要があります。

詳細な手順については、Capacitorドキュメントを参照してください。

このプラグインで必要な辞書キーはNSPrivacyAccessedAPICategoryUserDefaultsで、推奨される理由はCA92.1です。

PrivacyInfo.xcprivacyの例

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyAccessedAPITypes</key>
<array>
<!-- Add this dict entry to the array if the PrivacyInfo file already exists -->
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategoryUserDefaults</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>CA92.1</string>
</array>
</dict>
</array>
</dict>
</plist>

プラグインの使用例

import { Preferences } from '@capacitor/preferences';

const setName = async () => {
await Preferences.set({
key: 'name',
value: 'Max',
});
};

const checkName = async () => {
const { value } = await Preferences.get({ key: 'name' });

console.log(`Hello ${value}!`);
};

const removeName = async () => {
await Preferences.remove({ key: 'name' });
};

JSONの使用

Preferences APIは文字列値のみをサポートしています。ただし、set()を呼び出す前にオブジェクトをJSON.stringifyし、get()から返された値をJSON.parseすることでJSONを使用できます。

この方法は、数値やブール値などの文字列以外の値を保存するためにも使用できます。

API

configure(...)

configure(options: ConfigureOptions) => Promise<void>

Configure the preferences plugin at runtime.

Options that are undefined will not be used.

ParamType
options
ConfigureOptions

Since: 1.0.0


get(...)

get(options: GetOptions) => Promise<GetResult>

Get the value from preferences of a given key.

ParamType
options
GetOptions

Returns:

Promise<GetResult>

Since: 1.0.0


set(...)

set(options: SetOptions) => Promise<void>

Set the value in preferences for a given key.

ParamType
options
SetOptions

Since: 1.0.0


remove(...)

remove(options: RemoveOptions) => Promise<void>

Remove the value from preferences for a given key, if any.

ParamType
options
RemoveOptions

Since: 1.0.0


clear()

clear() => Promise<void>

Clear keys and values from preferences.

Since: 1.0.0


keys()

keys() => Promise<KeysResult>

Return the list of known keys in preferences.

Returns:

Promise<KeysResult>

Since: 1.0.0


migrate()

migrate() => Promise<MigrateResult>

Migrate data from the Capacitor 2 Storage plugin.

This action is non-destructive. It will not remove old data and will only write new data if they key was not already set. To remove the old data after being migrated, call removeOld().

Returns:

Promise<MigrateResult>

Since: 1.0.0


removeOld()

removeOld() => Promise<void>

Removes old data with _cap_ prefix from the Capacitor 2 Storage plugin.

Since: 1.1.0


Interfaces

ConfigureOptions

PropTypeDescriptionDefaultSince
groupstringSet the preferences group. Preferences groups are used to organize key/value pairs. Using the value 'NativeStorage' provides backwards-compatibility with cordova-plugin-nativestorage. WARNING: The clear() method can delete unintended values when using the 'NativeStorage' group.CapacitorStorage1.0.0

GetResult

PropTypeDescriptionSince
valuestring | nullThe value from preferences associated with the given key. If a value was not previously set or was removed, value will be null.1.0.0

GetOptions

PropTypeDescriptionSince
keystringThe key whose value to retrieve from preferences.1.0.0

SetOptions

PropTypeDescriptionSince
keystringThe key to associate with the value being set in preferences.1.0.0
valuestringThe value to set in preferences with the associated key.1.0.0

RemoveOptions

PropTypeDescriptionSince
keystringThe key whose value to remove from preferences.1.0.0

KeysResult

PropTypeDescriptionSince
keysstring[]The known keys in preferences.1.0.0

MigrateResult

PropTypeDescriptionSince
migratedstring[]An array of keys that were migrated.1.0.0
existingstring[]An array of keys that were already migrated or otherwise exist in preferences that had a value in the Capacitor 2 Preferences plugin.1.0.0