nativescript-imagepicker icon indicating copy to clipboard operation
nativescript-imagepicker copied to clipboard

No reliable way to determine selected media's type

Open nikoTM opened this issue 5 years ago • 5 comments

Both videos and images are returned as ImageAsset, how can we reliably determine mediaType from there?

nikoTM avatar Jan 27 '20 11:01 nikoTM

Any idea anyone?

pandabuilt avatar Apr 04 '21 16:04 pandabuilt


private resolveMediaType(path: string): string | CustomError {
    if (!path) {
      return new CustomError(
        this.translateService.instant('services.noFileProvided')
      );
    }
    try {
      if (isAndroid) {
        const cr = Application.android.context.getContentResolver();
        const file = new java.io.File(path);
        const sdkVersionInt = parseInt(Device.sdkVersion, 10);
        const pkgName = Utils.ad.getApplication().getPackageName();
        let mediaUri: string;
        if (sdkVersionInt >= 21) {
          const ContentNamespace =
            global.androidx && global.androidx.appcompat
              ? androidx.core.content
              : android.support.v4.content;
          mediaUri = ContentNamespace.FileProvider.getUriForFile(
            Application.android.foregroundActivity, // or app.android.currentContext ??
            `${pkgName}.provider`,
            file
          );
        } else {
          mediaUri = android.net.Uri.fromFile(file);
        }

        return cr.getType(mediaUri);
      } else if (isIOS) {
        const mediaType = (path as any).mediaType;

        switch (mediaType) {
          case PHAssetMediaType.Image:
            return 'image/*';
          case PHAssetMediaType.Video:
            return 'video/*';
        }

        return null;
      }
    } catch (e) {
      console.log(e);

      if (typeof path !== 'string') {
        return new CustomError(
          this.translateService.instant('services.unableToResolveMediaType')
        );
      }
      const possibleImageFormats = ['.jpg', '.jpeg', '.png'];
      return possibleImageFormats.some(format => path.endsWith(format))
        ? 'image/*'
        : new CustomError(
            this.translateService.instant('services.unableToResolveMediaType')
          );
    }
  }
  

@pandabuilt I use this as a workaround, path being ImageAsset.[android | ios]

nikoTM avatar Apr 04 '21 16:04 nikoTM

@nikoTM Can I see your imports? Or how do you get global.androidx, java and PHAssetMediaType

pandabuilt avatar Apr 05 '21 01:04 pandabuilt

@pandabuilt declare const global: any, java: any, PHAssetMediaType: any; those are available at runtime

nikoTM avatar Apr 06 '21 12:04 nikoTM

in 2.0.0, it will now return selection[0].type and be image|video.

davecoffin avatar Apr 18 '23 15:04 davecoffin