Skip to content

Instantly share code, notes, and snippets.

@Burgov
Created January 8, 2020 07:53
Show Gist options
  • Save Burgov/30ecf67a6fb0e036378fb69d7bda9108 to your computer and use it in GitHub Desktop.
Save Burgov/30ecf67a6fb0e036378fb69d7bda9108 to your computer and use it in GitHub Desktop.
import * as imagepicker from 'nativescript-imagepicker';
import { ImagePickerMediaType } from 'nativescript-imagepicker';
import { EMPTY, Observable } from 'rxjs';
import { knownFolders } from 'tns-core-modules/file-system';
import { fromFile } from 'tns-core-modules/image-source';
import * as dialogs from 'tns-core-modules/ui/dialogs';
import * as utils from 'tns-core-modules/utils/utils';
export declare const NO_IMAGE_SELECTED = 'no-image-selected';
export class MediaPicker {
pick(types) {
let mediaType = ImagePickerMediaType.Any;
if (types && types.length == 1) {
if (types[0] == 'image') {
mediaType = ImagePickerMediaType.Image;
} else {
mediaType = ImagePickerMediaType.Video;
}
}
return Observable.create(observer => {
const context = imagepicker.create({
mode: 'single',
mediaType: mediaType,
});
context
.authorize()
.catch(e => {
dialogs
.confirm(
"This app is not authorized to access photo's. Hit OK to go to the settings where this can be fixed.",
)
.then(result => {
if (result) {
utils.openUrl(
NSURL.URLWithString(UIApplicationOpenSettingsURLString)
.absoluteString,
);
}
});
return EMPTY;
})
.then(() => context.present())
.then(result => {
let r = result[0].ios as PHAsset;
if (r.mediaType == PHAssetMediaType.Image) {
r.requestContentEditingInputWithOptionsCompletionHandler(
new PHContentEditingInputRequestOptions(),
(contentEditingInput, info) => {
try {
let path = contentEditingInput.fullSizeImageURL.path;
if (!path.match(/\.(jpg|gif|png)$/)) {
const imageSource = fromFile(path);
const target = knownFolders.temp().path + '/image.jpg';
if (!imageSource.saveToFile(target, 'jpg')) {
return observer.error('Could not save file');
}
observer.next(target);
observer.complete();
}
observer.next(path);
observer.complete();
} catch (e) {
observer.error('Unable to process image file');
}
},
);
return;
} else if (r.mediaType == PHAssetMediaType.Video) {
PHImageManager.defaultManager().requestAVAssetForVideoOptionsResultHandler(
r,
new PHVideoRequestOptions(),
asset => {
try {
observer.next((asset as AVURLAsset).URL.path);
observer.complete();
} catch (e) {
observer.error('Unable to process video file');
}
},
);
return;
}
observer.error(new Error("Couldn't figure it out"));
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment