모바일 출입증 버튼을 탭하면 외부 앱으로 연결되도록 구현해야 한다.

image.png

이 때 딥링크 라는 개념을 알게 되었다.

딥링크

일반 링크와 달리, 링크 클릭 시 새로운 웹페이지로 이동하지 않고 특정 앱의 특정 경로까지 연결시켜준다.

이를 위해 각 OS 별 스킴(scheme) 을 등록해야 한다. — Duke


export function openApp({ androidScheme, iosScheme, fallbackUrl }) {
	const ua = navigator.userAgent.toLowerCase(); // user agent
	const isAndroid = ua.includes("android");
	const isIOS = /iphone|ipad|ipod/.test(ua);

	// 플랫폼에 맞는 스킴 선택
	const scheme = isAndroid ? androidScheme : isIOS ? iosScheme : null;
	
	const androidStoreUrl = "https://...." // 구글 플레이스토어 링크
	const iosStoreUrl = "https://...." // 애플 앱스토어 링크

	// 인앱 브라우저일 땐 사용자 안내
	if (!scheme) {
		// 여기서는 폴백 페이지로 안내하거나 "브라우저에서 열기" 알림을 보여주도록 처리
		window.location.href = fallbackUrl;
		return;
	}

	// 앱 실행 시도
	window.location.href = scheme;
	
	const now = Date.now();

	// 현재 시점 ~ 일정 시간 뒤에도 페이지가 바뀌지 않으면 → 앱 실행 실패로 판단
	setTimeout(() => {
		if (Date.now() - now < 1500) {
			if (isAndroid) {
				window.location.href = androidStoreUrl;
			} else if (isIOS) {
				window.location.href = iosStoreUrl;
			} else {
				window.location.href = fallbackUrl;
			}
		}
	}, 1000);
	}
<button
	onClick={() =>
		openApp({
			androidScheme: "cp4mid://action",
			iosScheme: "cp4mobileid://action",
			fallbackUrl: "<https://example.com/app-download>",
		})
	}
>
	앱으로 이동
</button>

User agent 란?

웹 브라우저 또는 앱이 서버에 자신을 알리기 위해 보내는 문자열 정보.

→ OS 정보, 렌더링 엔진, 브라우저 이름 및 버전 포함

Scheme 이란?

URL의 :// 이전 가장 앞부분

→ 이 링크를 어떤 식으로 처리할지 브라우저/OS에게 알려주는 약속

예: youtube://watch?v=abc123

모바일 앱은 자신만의 scheme을 등록할 수 있다.

image.png