[kotlin] 코틀린과 PWA(Progressive Web App) 개발

PWA(Progressive Web App)는 웹 애플리케이션과 네이티브 앱의 장점을 결합한 모바일 앱 형태입니다. PWA는 네트워크 연결 상태에 관계 없이 빠르고 안정적으로 작동하며, 오프라인에서도 작동합니다. 또한 푸시 알림, 홈 화면에 설치 가능, 앱 스토어 제출 불필요 등의 장점을 지니고 있습니다.

이번 포스트에서는 코틀린으로 PWA를 개발하는 방법을 살펴보겠습니다.

1. PWA 기본 개념

PWA는 다음과 같은 특징을 갖고 있습니다:

2. 코틀린으로 PWA 개발

코틀린을 사용하여 PWA를 개발하는 방법은 다음과 같습니다.

2.1. PWA 기본 설정

PWA를 개발하기 위해서는 먼저 웹 앱 매니페스트와 서비스 워커 등을 설정해야 합니다.

웹 앱 매니페스트 생성

{
  "name": "My PWA",
  "short_name": "PWA",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#fff",
  "theme_color": "#007bff",
  "icons": [
    {
      "src": "icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ]
}

서비스 워커 등록

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js')
      .then((registration) => {
        console.log('Service Worker registered with scope:', registration.scope);
      })
      .catch((error) => {
        console.error('Service Worker registration failed:', error);
      });
  });
}

2.2. 오프라인 지원 추가

서비스 워커를 사용하여 오프라인에서도 작동하도록 만들 수 있습니다.

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request)
      .then((response) => {
        return response || fetchAndCache(event.request);
      })
  );
});

function fetchAndCache(url) {
  return fetch(url)
    .then((response) => {
      const responseClone = response.clone();
      caches.open('my-cache').then((cache) => {
        cache.put(url, responseClone);
      });
      return response;
    })
    .catch(() => new Response('Offline'));
}

2.3. 푸시 알림 추가

푸시 알림을 사용하여 사용자에게 알림을 전송할 수 있습니다.

const publicVapidKey = '<Your Public VAPID Key>';
const privateVapidKey = '<Your Private VAPID Key>';

const subscribeOptions = {
  userVisibleOnly: true,
  applicationServerKey: urlB64ToUint8Array(publicVapidKey)
};

registration.pushManager.subscribe(subscribeOptions)
  .then((subscription) => {
    // Send subscription to server
  })
  .catch((error) => {
    console.error('Unable to subscribe:', error);
  });

3. PWA 배포

PWA를 배포하기 위해서는 HTTPS를 사용하고, 웹 앱 매니페스트 파일 및 서비스 워커를 등록해야 합니다.

결론

코틀린과 PWA를 사용하면 웹 애플리케이션을 모바일 앱과 유사한 경험으로 제공할 수 있습니다. 따라서 코틀린으로 PWA를 개발하여 뛰어난 사용자 경험을 제공하는 앱을 만들어보세요.