capturePhoto method
Future<MiniProgramCameraPhotoResult>
capturePhoto(
{ - required String miniProgramId,
- required int quality,
- int? maxWidth,
- int? maxHeight,
})
Implementation
Future<MiniProgramCameraPhotoResult> capturePhoto({
required String miniProgramId,
required int quality,
int? maxWidth,
int? maxHeight,
}) async {
_ensureActive();
if (_activeByApp.isNotEmpty) {
throw const MiniProgramCameraException(
errorCode: MiniProgramErrorCodes.cameraRequestInProgress,
message: 'A photo capture request is already in progress.',
);
}
_sequence++;
final captureId =
'capture_${DateTime.now().microsecondsSinceEpoch}_$_sequence';
_activeByApp[miniProgramId] = captureId;
try {
final result = await provider.capturePhoto(
MiniProgramCameraCaptureRequest(
captureId: captureId,
miniProgramId: miniProgramId,
quality: quality,
maxWidth: maxWidth,
maxHeight: maxHeight,
),
);
if (_cancelledCaptureIds.remove(captureId)) {
await _releaseBestEffort(result.mediaRef);
throw const MiniProgramCameraException(
errorCode: MiniProgramErrorCodes.cameraCaptureCancelled,
message: 'Photo capture was cancelled.',
);
}
if (result.captureId != captureId ||
_mediaOwners.containsKey(result.mediaRef) ||
(mediaManager?.owns(miniProgramId, result.mediaRef) ?? false)) {
await _releaseBestEffort(result.mediaRef);
throw const MiniProgramCameraException(
errorCode: MiniProgramErrorCodes.cameraInvalidResult,
message: 'The host returned an invalid camera reference.',
);
}
result.validate();
final sharedMedia = mediaManager;
if (sharedMedia == null) {
_mediaOwners[result.mediaRef] = miniProgramId;
} else {
try {
sharedMedia.register(
miniProgramId: miniProgramId,
mediaRef: result.mediaRef,
);
} on MiniProgramMediaException {
await _releaseBestEffort(result.mediaRef);
throw const MiniProgramCameraException(
errorCode: MiniProgramErrorCodes.cameraInvalidResult,
message: 'The host returned an invalid camera reference.',
);
}
}
return result;
} on FormatException catch (error) {
throw MiniProgramCameraException(
errorCode: MiniProgramErrorCodes.cameraInvalidResult,
message: error.message.toString(),
);
} finally {
_cancelledCaptureIds.remove(captureId);
if (_activeByApp[miniProgramId] == captureId) {
_activeByApp.remove(miniProgramId);
}
}
}