Skip to content

네이티브 기능 사용하기

@apps-in-toss/web-framework를 사용하면 일반 웹 프로젝트에서도 네이티브 기능을 쉽게 사용할 수 있어요
React Native에서 제공하는 기능을 웹에서도 같은 방식으로 사용할 수 있어서, 기존 레퍼런스를 참고하면 돼요.

네이티브 기능 사용 방법

  1. import 문으로 원하는 기능을 불러와요.
  2. 해당 함수를 사용해서 원하는 동작을 수행해요.
  3. 버튼 클릭이나 이벤트와 연결해서 실행할 수도 있어요.

아래 예제에서 대표적인 기능을 확인할 수 있어요.

예제 1: getDeviceId로 기기 정보 가져오기

기기의 고유 ID를 가져오려면 getDeviceId를 사용해요. 이 함수는 앱 내에서 특정 기기를 구분할 때 유용해요.

tsx
import { getDeviceId } from "@apps-in-toss/web-framework";
import { useState } from "react";

const DeviceInfo = () => {
  const [deviceId, setDeviceId] = useState<string | null>(null);

  const fetchDeviceId = async () => {
    setDeviceId(getDeviceId());
  };

  return (
    <div>
      <button onClick={fetchDeviceId}>기기 ID 가져오기</button>
      {deviceId && <p>Device ID: {deviceId}</p>}
    </div>
  );
};
tsx
import { getDeviceId } from "@apps-in-toss/web-framework";

const fetchDeviceId = async () => {
  console.log("Device ID:", getDeviceId());
};

document.addEventListener("DOMContentLoaded", () => {
  const button = document.createElement("button");
  button.textContent = "기기 ID 가져오기";
  button.addEventListener("click", fetchDeviceId);
  document.body.appendChild(button);
});

예제 2: 공유 기능 사용하기

share 함수를 사용하면 특정 메시지를 네이티브 공유 기능을 통해 공유할 수 있어요.
예를 들어, 사용자에게 앱을 추천하거나 이벤트 정보를 공유할 때 활용할 수 있어요.

tsx
import { share } from "@apps-in-toss/web-framework";

const ShareButton = () => {
  const handleShare = async () => {
    try {
      await share({ message: "공유할 메시지" });
      console.log("공유 완료");
    } catch (error) {
      console.error("공유 실패:", error);
    }
  };

  return <button onClick={handleShare}>공유하기</button>;
};
tsx
import { share } from "@apps-in-toss/web-framework";

const handleShare = async () => {
  try {
    await share({ message: "공유할 메시지" });
    console.log("공유 완료");
  } catch (error) {
    console.error("공유 실패:", error);
  }
};

document.addEventListener("DOMContentLoaded", () => {
  const button = document.createElement("button");
  button.textContent = "공유하기";
  button.addEventListener("click", handleShare);
  document.body.appendChild(button);
});

예제 3: 토스 인증으로 로그인하기

appLogin을 사용하면 사용자가 토스 인증을 통해 로그인할 수 있어요.
이 기능을 활용하면 네이티브 앱에서 안전한 인증을 쉽게 구현할 수 있어요.

tsx
import { appLogin } from "@apps-in-toss/web-framework";

const LoginButton = () => {
  const handleLogin = async () => {
    try {
      const { authorizationCode, referrer } = await appLogin();
      console.log("Authorization Code:", authorizationCode);
      /* 이후 authorizationCode 와 referrer 를 서버에 전달 */
    } catch (error) {
      console.error("로그인 실패:", error);
    }
  };

  return <button onClick={handleLogin}>토스 인증으로 로그인</button>;
};
tsx
import { appLogin } from "@apps-in-toss/web-framework";

const handleLogin = async () => {
  try {
    const { authorizationCode } = await appLogin();
    console.log("Authorization Code:", authorizationCode);
  } catch (error) {
    console.error("로그인 실패:", error);
  }
};

document.addEventListener("DOMContentLoaded", () => {
  const button = document.createElement("button");
  button.textContent = "토스 인증으로 로그인";
  button.addEventListener("click", handleLogin);
  document.body.appendChild(button);
});

예제 4: 위치 정보 지속적으로 감지하기

startUpdateLocation을 사용하면 사용자의 위치 정보를 지속적으로 감지하고, 위치가 변경될 때마다 콜백 함수를 실행할 수 있어요. 이 기능은 실시간 위치 추적이 필요한 서비스에 유용해요. 예를 들어 지도 앱에서 사용자의 현재 위치를 실시간으로 표시하거나, 운동 앱에서 이동 거리를 기록할 때 활용할 수 있어요.

tsx
import { startUpdateLocation, Accuracy } from "@apps-in-toss/web-framework";
import { useEffect, useRef } from "react";

function LocationWatcher() {
  const [location, setLocation] = useState(null);

  useEffect(() => {
    return startUpdateLocation({
      options: {
        accuracy: Accuracy.Balanced,
        timeInterval: 3000,
        distanceInterval: 10,
      },
      onEvent: (location) => {
        setLocation(location);
      },
      onError: (error) => {
        console.error("위치 정보를 가져오는데 실패했어요:", error);
      },
    });
  }, []);

  if (location == null) {
    return <p>위치 정보를 가져오는 중이에요...</p>;
  }

  return (
    <div>
      <p>위도: {location.coords.latitude}</p>
      <p>경도: {location.coords.longitude}</p>
      <p>위치 정확도: {location.coords.accuracy}m</p>
      <p>높이: {location.coords.altitude}m</p>
      <p>고도 정확도: {location.coords.altitudeAccuracy}m</p>
      <p>방향: {location.coords.heading}°</p>
    </div>
  );
}
tsx
import { startUpdateLocation, Accuracy } from "@apps-in-toss/web-framework";

let unsubscription = null;

const handleStartLocationUpdates = () => {
  unsubscription = startUpdateLocation({
    onError: (error) => console.error("위치 정보를 가져오지 못했어요:", error),
    onEvent: (response) => console.log("현재 위치:", response),
    options: {
      accuracy: Accuracy.Balanced,
      distanceInterval: 1,
      timeInterval: 1000,
    },
  });
  console.log("위치 추적 시작");
};

const handleStopLocationUpdates = () => {
  if (unsubscription) {
    unsubscription();
    unsubscription = null;
    console.log("위치 추적 중지");
  }
};

document.addEventListener("DOMContentLoaded", () => {
  const startButton = document.createElement("button");
  startButton.textContent = "위치 추적 시작";
  startButton.addEventListener("click", handleStartLocationUpdates);

  const stopButton = document.createElement("button");
  stopButton.textContent = "위치 추적 중지";
  stopButton.addEventListener("click", handleStopLocationUpdates);

  document.body.appendChild(startButton);
  document.body.appendChild(stopButton);
});