PHPickerViewController: pick event
The pick event fires when the user finishes picking or taps Cancel. The event object's results holds the picked items.
Syntax
picker.addEventListener('pick', (event) => { })Event object
An Event, with one extra field:
results
An array of PHPickerResult, read-only (frozen). An empty array when the user tapped Cancel. When selection is 'ordered' or 'continuousAndOrdered', the items are in the order the user picked them.
The listener receives a parameter of type Event; to read results, cast it once: /** @type {PHPickerViewControllerFinishEvent} */ (event).
Not cancelable. The callback runs in the next turn after the event occurs.
When it fires
The photo picker can finish in three ways:
| What the user did | What fires |
|---|---|
| Finished picking and tapped "Add" at the top right. When only one item may be picked, tapping that item counts as finishing | pick, with results holding the picked items |
| Tapped "Cancel" at the top left | pick, with results an empty array |
| Dragged the picker down | The view controller's dismiss event. Whether a pick with empty results also fires is not verified in the simulator |
- The photo picker doesn't close itself. After
pickfires it is still on screen; calldismissViewController()in the listener. What happens if you calldismissViewController()again on a picker that has already been dragged away is not verified in the simulator. - When
selectionis'continuous'or'continuousAndOrdered', it fires each time an item is selected or deselected, withresultsholding everything selected at that moment. In these modes, don't close the picker in the listener. - A
pickevent you fire yourself withdispatchEvent()has noresults.
Examples
const page = new UIViewController();
const picker = new PHPickerViewController(new PHPickerConfiguration());
picker.addEventListener('pick', (event) => {
const { results } = /** @type {PHPickerViewControllerFinishEvent} */ (event);
picker.dismissViewController({ animated: true });
console.log(results.length === 0 ? 'Canceled' : 'Picked ' + results.length + ' item(s)');
});
page.presentViewController(picker, { animated: true });Effect (not verified in the simulator): When the user picks one item, the photo picker disappears and the console prints Picked 1 item(s). When the user taps "Cancel", it prints Canceled.
Corresponding iOS API
The delegate method picker:didFinishPicking:. In JS, instead of setting a delegate, listen for this event; the results parameter is on the event object.
See also
PHPickerResult: the type of each item inresultsNSItemProvider: loading images from picked items- Picking photos and saving them to the photo library
- This class belongs to the
@nacrejs/photospackage; for how to install it, see Install first