| 1 |
''' |
| 2 |
IOS file chooser |
| 3 |
-------------------- |
| 4 |
|
| 5 |
This module houses the iOS implementation of the plyer FileChooser. |
| 6 |
|
| 7 |
.. versionadded:: 1.4.4 |
| 8 |
''' |
| 9 |
|
| 10 |
from plyer.facades import FileChooser |
| 11 |
from pyobjus import autoclass, protocol |
| 12 |
from pyobjus.dylib_manager import load_framework |
| 13 |
|
| 14 |
|
| 15 |
load_framework('/System/Library/Frameworks/Photos.framework') |
| 16 |
|
| 17 |
|
| 18 |
class IOSFileChooser(FileChooser): |
| 19 |
''' |
| 20 |
FileChooser implementation for IOS using |
| 21 |
the built-in file browser via UIImagePickerController. |
| 22 |
|
| 23 |
.. versionadded:: 1.4.0 |
| 24 |
''' |
| 25 |
|
| 26 |
def __init__(self, *args, **kwargs): |
| 27 |
super().__init__(*args, **kwargs) |
| 28 |
self._on_selection = None |
| 29 |
|
| 30 |
def _file_selection_dialog(self, *args, **kwargs): |
| 31 |
""" |
| 32 |
Function called when action is required, A "mode" parameter specifies |
| 33 |
which and is one of "open", "save" or "dir". |
| 34 |
""" |
| 35 |
self._on_selection = kwargs["on_selection"] |
| 36 |
if kwargs["mode"] == "open": |
| 37 |
self._open() |
| 38 |
else: |
| 39 |
raise NotImplementedError() |
| 40 |
|
| 41 |
def _get_picker(self): |
| 42 |
""" |
| 43 |
Return an instantiated and configured UIImagePickerController. |
| 44 |
""" |
| 45 |
picker = autoclass("UIImagePickerController") |
| 46 |
po = picker.alloc().init() |
| 47 |
po.sourceType = 0 |
| 48 |
po.delegate = self |
| 49 |
return po |
| 50 |
|
| 51 |
def _open(self): |
| 52 |
""" |
| 53 |
Launch the native iOS file browser. Upon selection, the |
| 54 |
`imagePickerController_didFinishPickingMediaWithInfo_` delegate is |
| 55 |
called where we close the file browser and handle the result. |
| 56 |
""" |
| 57 |
picker = self._get_picker() |
| 58 |
UIApplication = autoclass('UIApplication') |
| 59 |
vc = UIApplication.sharedApplication().keyWindow.rootViewController() |
| 60 |
vc.presentViewController_animated_completion_(picker, True, None) |
| 61 |
|
| 62 |
@protocol('UIImagePickerControllerDelegate') |
| 63 |
def imagePickerController_didFinishPickingMediaWithInfo_( |
| 64 |
self, image_picker, frozen_dict): |
| 65 |
""" |
| 66 |
Delegate which handles the result of the image selection process. |
| 67 |
""" |
| 68 |
image_picker.dismissViewControllerAnimated_completion_(True, None) |
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
native_image_picker = autoclass("NativeImagePicker").alloc().init() |
| 76 |
path = native_image_picker.writeToPNG_(frozen_dict) |
| 77 |
self._on_selection([path.UTF8String()]) |
| 78 |
|
| 79 |
|
| 80 |
def instance(): |
| 81 |
return IOSFileChooser() |