はじめに
Copy a setup prompt with the install steps and the full markdown guide for this plugin.
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/capacitor-wifi`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/ja/docs/plugins/wifi/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
-
パッケージのインストール
Terminal window npm i @capgo/capacitor-wifiTerminal window pnpm add @capgo/capacitor-wifiTerminal window yarn add @capgo/capacitor-wifiTerminal window bun add @capgo/capacitor-wifi -
ネイティブプロジェクトと同期
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window bunx cap sync -
パーミッションの設定
Android:
AndroidManifest.xmlに追加:<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /><uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />iOS:
Info.plistに追加:<key>NSLocationWhenInUseUsageDescription</key><string>WiFiネットワークをスキャンするには位置情報へのアクセスが必要です</string>
プラグインをインポートしてWiFi接続を管理します:
import { CapacitorWifi } from '@capgo/capacitor-wifi';
// 現在のWiFi接続情報を取得const getWifiInfo = async () => { const info = await CapacitorWifi.getWifiInfo(); console.log('接続先:', info.ssid); console.log('IPアドレス:', info.ip);};
// 利用可能なネットワークをスキャンconst scanNetworks = async () => { const { networks } = await CapacitorWifi.scan(); networks.forEach(network => { console.log(`SSID: ${network.ssid}, 信号: ${network.level}`); });};
// ネットワークに接続const connectToWifi = async () => { await CapacitorWifi.connect({ ssid: 'MyNetwork', password: 'mypassword' });};APIリファレンス
Section titled “APIリファレンス”getWifiInfo()
Section titled “getWifiInfo()”現在接続されているWiFiネットワークの情報を取得します。
interface WifiInfo { ssid: string; // ネットワーク名 bssid: string; // アクセスポイントのMACアドレス ip: string; // デバイスのIPアドレス frequency: number; // ネットワーク周波数(MHz) linkSpeed: number; // 接続速度(Mbps) signalStrength: number; // 信号強度(0-100)}
const info = await CapacitorWifi.getWifiInfo();scan()
Section titled “scan()”利用可能なWiFiネットワークをスキャンします。
interface WifiNetwork { ssid: string; // ネットワーク名 bssid: string; // MACアドレス level: number; // 信号レベル(dBm) frequency: number; // ネットワーク周波数 capabilities: string; // セキュリティ機能}
const { networks } = await CapacitorWifi.scan();connect(options)
Section titled “connect(options)”WiFiネットワークに接続します。
interface ConnectOptions { ssid: string; // ネットワーク名 password?: string; // ネットワークパスワード(保護されている場合) isHiddenSsid?: boolean; // SSIDが非表示かどうか}
await CapacitorWifi.connect({ ssid: 'MyNetwork', password: 'mypassword'});disconnect()
Section titled “disconnect()”現在のWiFiネットワークから切断します。
await CapacitorWifi.disconnect();getSSID()
Section titled “getSSID()”現在接続されているネットワークのSSIDを取得します。
const { ssid } = await CapacitorWifi.getSSID();console.log('接続先:', ssid);getIP()
Section titled “getIP()”現在のデバイスのIPアドレスを取得します。
const { ip } = await CapacitorWifi.getIP();console.log('IPアドレス:', ip);import { CapacitorWifi } from '@capgo/capacitor-wifi';
export class WifiService { async getCurrentNetwork() { try { const info = await CapacitorWifi.getWifiInfo(); return { name: info.ssid, strength: this.getSignalQuality(info.signalStrength), speed: `${info.linkSpeed} Mbps`, ip: info.ip }; } catch (error) { console.error('Failed to get WiFi info:', error); return null; } }
async scanAndConnect(targetSsid: string, password: string) { try { // Scan for networks const { networks } = await CapacitorWifi.scan();
// Find target network const targetNetwork = networks.find(n => n.ssid === targetSsid);
if (!targetNetwork) { throw new Error(`Network ${targetSsid} not found`); }
console.log(`Found network with signal: ${targetNetwork.level} dBm`);
// Connect to network await CapacitorWifi.connect({ ssid: targetSsid, password: password });
console.log('Connected successfully!'); return true; } catch (error) { console.error('Connection failed:', error); return false; } }
async findBestNetwork(preferredNetworks: string[]) { const { networks } = await CapacitorWifi.scan();
// Filter to preferred networks const available = networks.filter(n => preferredNetworks.includes(n.ssid) );
if (available.length === 0) { return null; }
// Sort by signal strength available.sort((a, b) => b.level - a.level);
return available[0]; }
async monitorConnection(callback: (info: WifiInfo | null) => void) { const checkConnection = async () => { try { const info = await CapacitorWifi.getWifiInfo(); callback(info); } catch (error) { callback(null); } };
// Check every 5 seconds const interval = setInterval(checkConnection, 5000);
// Initial check await checkConnection();
// Return cleanup function return () => clearInterval(interval); }
private getSignalQuality(strength: number): string { if (strength >= 80) return '優秀'; if (strength >= 60) return '良好'; if (strength >= 40) return '普通'; return '弱い'; }
async getNetworkSecurity(ssid: string): Promise<string> { const { networks } = await CapacitorWifi.scan(); const network = networks.find(n => n.ssid === ssid);
if (!network) { return 'Unknown'; }
const caps = network.capabilities.toLowerCase();
if (caps.includes('wpa3')) return 'WPA3'; if (caps.includes('wpa2')) return 'WPA2'; if (caps.includes('wpa')) return 'WPA'; if (caps.includes('wep')) return 'WEP';
return 'Open'; }}高度な使用方法
Section titled “高度な使用方法”ネットワーク品質評価
Section titled “ネットワーク品質評価”const assessNetworkQuality = async () => { const info = await CapacitorWifi.getWifiInfo();
const quality = { signal: info.signalStrength >= 70 ? '優秀' : info.signalStrength >= 50 ? '良好' : info.signalStrength >= 30 ? '普通' : '弱い', speed: info.linkSpeed >= 100 ? '高速' : info.linkSpeed >= 50 ? '中速' : '低速', frequency: info.frequency >= 5000 ? '5GHz' : '2.4GHz' };
console.log('ネットワーク品質:', quality); return quality;};優先ネットワークへの自動接続
Section titled “優先ネットワークへの自動接続”const autoConnect = async (preferredNetworks: Array<{ ssid: string, password: string }>) => { const { networks } = await CapacitorWifi.scan();
for (const preferred of preferredNetworks) { const found = networks.find(n => n.ssid === preferred.ssid);
if (found) { try { await CapacitorWifi.connect({ ssid: preferred.ssid, password: preferred.password }); console.log(`Connected to ${preferred.ssid}`); return true; } catch (error) { console.error(`Failed to connect to ${preferred.ssid}`); } } }
return false;};ネットワーク変更検出
Section titled “ネットワーク変更検出”class NetworkMonitor { private currentSsid: string | null = null; private listeners: Array<(ssid: string | null) => void> = [];
async start() { setInterval(async () => { try { const { ssid } = await CapacitorWifi.getSSID();
if (ssid !== this.currentSsid) { this.currentSsid = ssid; this.notifyListeners(ssid); } } catch (error) { if (this.currentSsid !== null) { this.currentSsid = null; this.notifyListeners(null); } } }, 3000); }
onNetworkChange(callback: (ssid: string | null) => void) { this.listeners.push(callback); }
private notifyListeners(ssid: string | null) { this.listeners.forEach(listener => listener(ssid)); }}ベストプラクティス
Section titled “ベストプラクティス”- パーミッション: ネットワークをスキャンする前に位置情報パーミッションをリクエスト
- エラー処理: WiFi操作は常にtry-catchブロックでラップ
- ユーザーフィードバック: ネットワーク操作中はローディングインジケーターを表示
- セキュリティ: WiFiパスワードを平文で保存しない
- テスト: WiFi APIはエミュレーターで動作しない可能性があるため、実デバイスでテスト
プラットフォームの違い
Section titled “プラットフォームの違い”- ネットワークをスキャンするには位置情報パーミッションが必要
- プログラム的にネットワークに接続できない(設定アプリを開く)
- ネットワーク詳細へのアクセスが制限されている
Android
Section titled “Android”- 完全なプログラム的WiFi制御
- ネットワークスキャンには位置情報パーミッションが必要
- プログラム的に接続/切断が可能
トラブルシューティング
Section titled “トラブルシューティング”よくある問題
Section titled “よくある問題”スキャンが空を返す: 位置情報パーミッションが許可されているか確認 ネットワークに接続できない: パスワードが正しく、ネットワークが範囲内にあるか確認 getWifiInfoが失敗する: デバイスがWiFiネットワークに接続されているか確認 パーミッション拒否: プラットフォーム設定ファイルに必要なパーミッションを追加