Выставка не является точной, особенно на iOSIOS

Программируем под IOS
Ответить
Anonymous
 Выставка не является точной, особенно на iOS

Сообщение Anonymous »

Я использую этот пакет экспозиции для получения текущего местоположения пользователя и выставки Camera
Проблема в том, что иногда-, особенно на устройствах iOS -местоположение неточно и может быть отключено более чем на 1 км от реальной позиции. Я разрабатываю сканер QR для посещаемости событий
, поэтому у меня есть файл scanner.tsx , который служит страницей сканера в моем приложении. Когда пользователь перейдет на эту страницу, приложение должно запросить два разрешения: разрешение на местоположение и разрешение на камеру .
Затем, когда пользователь сканирует код QR с помощью камеры, приложение

/> < /ol>
Я также реализую Sentry, чтобы поймать любую ошибку со стороны пользователя, и получил это < /p>

Код: Выделить всё

NSGenericException
*** -[AVCaptureSession startRunning] startRunning may not be called between calls to beginConfiguration and commitConfiguration
Не уверен, что это имеет значение, поскольку некоторые пользователи iOS могут правильно сканировать, а местоположение также точно
Вот мой app.json Файл:

"plugins": [
...
[
"expo-camera",
{
"cameraPermission": "This allows you to capture a photo using your camera to update your profile picture and scan an event QR code.",
"microphonePermission": "Allow $(PRODUCT_NAME) to access your microphone",
"recordAudioAndroid": true
}
],
[
"expo-location",
{
"locationAlwaysAndWhenInUsePermission": "Allow $(PRODUCT_NAME) to use your location."
}
],
...
]

Вот мой scanner.tsx
export default function Scanner() {
const [facing] = useState('back')
const [cameraPermission, requestCameraPermission] = useCameraPermissions()
const [locationPermission, setLocationPermission] =
useState()
const oneSignalSubscription = useSelector(
({ oneSignal }: any) => oneSignal.subscription,
)
const [isScanning, setIsScanning] = useState(false)
const [showTorch, setShowTorch] = useState(false)
const [modalContent, setModalContent] = useState(null)
const sheetRef = useRef(null)

useEffect(() => {
askPermission()
}, [])

const handleOnScan = async (scanningResult: BarcodeScanningResult) => {
if (isScanning) {
return
}

setIsScanning(true)
const codeValue = scanningResult.data

try {
const parsedURL = new URL(codeValue)

if (parsedURL.hostname !== 'myapp.app.link') {
Toast.show({
type: 'error',
text2: 'Not a Valid QR',
})
} else {
const { data: linkData }: any = await Api.postRequest(
'read-deep-link',
{ link: codeValue },
)

if (
linkData &&
linkData?.event_id &&
linkData?.type === 'mark-attend-event'
) {
await handleMarkAttendance(linkData.event_id)
} else {
setModalContent(codeValue)
sheetRef.current?.present()
}
}
} catch (err) {
setModalContent(codeValue)
sheetRef.current?.present()
} finally {
setTimeout(() => setIsScanning(false), 1000)
}
}

const handleMarkAttendance = async (eventId: any) => {
const location = await getCurrentLocation()
if (!location) {
Toast.show({
type: 'error',
text2: 'Please enable GPS/location services on your device.',
})
return
}

const postData = {
eventId,
deviceId: oneSignalSubscription.current?.id,
deviceType: Platform.OS,
geolocation: [
location?.coords.latitude,
location?.coords.longitude,
],
}
Api.postRequest('events/mark-attendance', postData)
.then(({ data }: any) => {
Toast.show({
type: 'success',
text2: data.message,
})
router.replace('/auth/event/success-scan')
})
.catch(error => {
const defaultMessage =
'There is an unexpected error while recording your attendance.'
Toast.show({
type: 'error',
text2: getFetchErrorMessage(error, defaultMessage),
})
})
}

const getCurrentLocation = async () => {
try {
let location = await Location.getCurrentPositionAsync({
accuracy: Location.LocationAccuracy.High,
})

return location
} catch (error) {
return null
}
}

const askLocationPermission = async () => {
return await Location.requestForegroundPermissionsAsync()
}

const askPermission = async () => {
const [cameraPermission, locationPermission] = await Promise.all([
requestCameraPermission(),
askLocationPermission(),
])
setLocationPermission(locationPermission)

let text = null
if (!cameraPermission.granted && !locationPermission.granted) {
text =
'Please enable camera and location access in your phone settings'
} else if (!cameraPermission.granted) {
text = 'Please enable camera access in your phone settings'
} else if (!locationPermission.granted) {
text = 'Please enable location access in your phone settings'
}

if (text !== null) {
Toast.show({
type: 'error',
text2: text,
onPress: () => openSettings(),
})
}
}

const copyToClip = async () => {
if (modalContent) {
await Clipboard.setStringAsync(modalContent)
sheetRef.current?.dismiss()
Toast.show({
type: 'success',
text2: 'Success copy to clipboard',
})
}
}

if (!cameraPermission) {
return
}

if (!cameraPermission.granted || !locationPermission?.granted) {
return (




We need your permission to access location and camera


Grant Permission



)
}

return (






setShowTorch(val => !val)}
>




Place QR Code in the box above



{isScanning && (



)}







{modalContent}









)
}
< /code>
Есть ли что -то не так с моей реализацией или логикой? Не стесняйтесь спрашивать, нужна ли вам больше деталей.


Подробнее здесь: https://stackoverflow.com/questions/796 ... lly-on-ios
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»