Files
o2o-weather/mobile/src/lib/share-image.ts
T

36 lines
1.4 KiB
TypeScript

import * as Sharing from 'expo-sharing';
import type { RefObject } from 'react';
import { Share, type View } from 'react-native';
import { captureRef } from 'react-native-view-shot';
import { track } from '@/lib/analytics';
import { useShareReward } from '@/lib/level';
type ShareText = { title: string; message: string };
/** 보이는 화면 조각을 PNG로 찍어 공유. 이미지 공유가 안 되는 곳(웹 등)이면 글로 보낸다. 보냈으면 true */
async function shareView(ref: RefObject<View | null>, { title, message }: ShareText) {
try {
if (ref.current && (await Sharing.isAvailableAsync())) {
const uri = await captureRef(ref, { format: 'png', quality: 1, result: 'tmpfile' });
await Sharing.shareAsync(uri, { mimeType: 'image/png', UTI: 'public.png', dialogTitle: title });
// 앱은 보이는 카드를 그대로 찍어 보내므로 비율은 'card'
track('share', { content_type: 'image', item_id: title, method: 'share_sheet', ratio: 'card' });
return true;
}
const res = await Share.share({ message });
return res.action === Share.sharedAction;
} catch (e) {
console.warn('공유 실패', e);
return false;
}
}
/** 화면 조각 공유. 보내면 하루 한 번 각을 받는다 (로그인했을 때만) */
export function useShare() {
const reward = useShareReward();
return async (ref: RefObject<View | null>, text: ShareText) => {
if (await shareView(ref, text)) reward();
};
}