feat: add QRCode scanner

This commit is contained in:
2025-12-17 23:57:04 +07:00
parent 5b5fcf9d44
commit bec77d187d
9 changed files with 1067 additions and 75 deletions

View File

@@ -0,0 +1,82 @@
import { BarcodeScanner } from "@capacitor-community/barcode-scanner";
import { Capacitor } from "@capacitor/core";
export interface QRScanResult {
text: string;
format: string;
}
export function useQRScanner() {
const isSupported = Capacitor.isNativePlatform();
// 检查权限
const checkPermission = async (): Promise<boolean> => {
try {
const status = await BarcodeScanner.checkPermission({ force: true });
return status.granted || false;
}
catch (error) {
console.error("Permission check failed:", error);
return false;
}
};
// 开始扫描
const startScan = async (): Promise<QRScanResult | null> => {
try {
// 检查是否为原生平台
if (!isSupported) {
console.warn("QR Scanner is only supported on native platforms");
return null;
}
// 检查权限
const hasPermission = await checkPermission();
if (!hasPermission) {
throw new Error("Camera permission denied");
}
// 隐藏背景以显示相机预览
await BarcodeScanner.hideBackground();
// 开始扫描
const result = await BarcodeScanner.startScan();
// 恢复背景
await BarcodeScanner.showBackground();
if (result?.hasContent) {
return {
text: result.content,
format: result.format || "QR_CODE",
};
}
return null;
}
catch (error) {
// 确保恢复背景
await BarcodeScanner.showBackground();
console.error("QR scan failed:", error);
throw error;
}
};
// 停止扫描
const stopScan = async () => {
try {
await BarcodeScanner.stopScan();
await BarcodeScanner.showBackground();
}
catch (error) {
console.error("Stop scan failed:", error);
}
};
return {
isSupported,
checkPermission,
startScan,
stopScan,
};
}