def __get_albums(type, subtype): # Helper function: constructs dictionary with user / smart albums # Sort albums in ascending order, based on their localized title PHAssetCollection = ObjCClass("PHAssetCollection") NSSortDescriptor = ObjCClass("NSSortDescriptor") PHFetchOptions = ObjCClass("PHFetchOptions") fetchOptions = PHFetchOptions.alloc().init().autorelease() fetchOptions.sortDescriptors = [ NSSortDescriptor.sortDescriptorWithKey_ascending_( "localizedTitle", True) ] # Fetch the albums with the specified type and return a list of their unique identifiers result = PHAssetCollection.fetchAssetCollectionsWithType_subtype_options_( type, subtype, fetchOptions) albums = dict() for index in range(result.count()): # Get each PHAssetCollection object and save (key,value) = (title,identifier) collection = result.objectAtIndex_(index) if type == __SMART_ALBUM: albums[__localized_smart_album_title( collection.assetCollectionSubtype())] = str( collection.localIdentifier()) else: albums[str(collection.localizedTitle())] = str( collection.localIdentifier()) # Return the dictionary with titles and identifiers return albums
def __get_asset_count(album, media_type): PHAsset = ObjCClass("PHAsset") NSPredicate = ObjCClass("NSPredicate") PHFetchOptions = ObjCClass("PHFetchOptions") fetchOptions = PHFetchOptions.alloc().init().autorelease() fetchOptions.predicate = NSPredicate.predicateWithFormat_("mediaType==" + str(media_type)) assets = PHAsset.fetchAssetsInAssetCollection_options_(album, fetchOptions) return assets.count()
def __init__(self, cla=''): self.class_name = cla self.obs = [] try: c = ObjCClass(self.class_name) except ValueError: dialogs.alert(self.class_name + ' is not a known class') try: self.obs.append(['Class',dir(c.alloc())]) except: pass
def __init__(self, cla=''): self.class_name = cla self.obs = [] try: c = ObjCClass(self.class_name) except ValueError: dialogs.alert(self.class_name + ' is not a known class') try: self.obs.append(['Class', dir(c.alloc())]) except: pass
def __init__(self, **kwargs): super().__init__(**kwargs) UIPickerView = ObjCClass('UIPickerView') self._picker_view = UIPickerView.alloc().initWithFrame_(ObjCInstance(self).bounds()).autorelease() ObjCInstance(self).addSubview_(self._picker_view) self.delegate_and_datasource = UIPickerViewDataSourceAndDelegate.alloc().init().autorelease() self._picker_view.delegate = self.delegate_and_datasource self._picker_view.dataSource = self.delegate_and_datasource self._picker_view.assets = photos.get_assets() self._picker_view.myRowWidth = self.width self._picker_view.myRowHeight = int(self.height/5)
def __get_album_dates(album): PHAsset = ObjCClass("PHAsset") NSSortDescriptor = ObjCClass("NSSortDescriptor") PHFetchOptions = ObjCClass("PHFetchOptions") fetchOptions = PHFetchOptions.alloc().init().autorelease() fetchOptions.sortDescriptors = [ NSSortDescriptor.sortDescriptorWithKey_ascending_( "creationDate", True) ] result = PHAsset.fetchAssetsInAssetCollection_options_(album, fetchOptions) if result.count() != 0: start_date = result.firstObject().creationDate() end_date = result.lastObject().creationDate() return (start_date, end_date) else: return (None, None)
def mail_compose( subject: str = "", recipients: Optional[List[str]] = None, body: str = "", filename: str = '', mime_type: str = '', dismiss_callback: Optional[Callable[[], None]] = None) -> None: """ Modal mail compose view. Display a modal mail compose view, with pre-populated contents, on top of the currently displayed view. The function returns immediately. Use argument `dismiss_callback` if your application needs to be notified when the compose view is dismissed. Arguments --------- subject: `str`, defaults to ``""`` Mail subject. recipients: `Optional[List[str]]`, defaults to ``None`` List of mail addresses for the recipients of the email. body: `str`, defaults to ``""`` Mail body. filename: `str`, defaults to ``''`` If non-empty, name of a file to be attached to the email. mime_type: `str`, defaults to ``''`` If `filename` is not empty, indicates the mime type of its contents, for instance ``'image/gif'`` dismiss_callback: `Optional[Callable[[], None]]`, defaults to ``None`` When set to a callable, it is called (with no arguments) when the mail composition view is dismissed. """ def mailComposeController_didFinishWithResult_error_( self, sel, controller, result, error): nonlocal dismiss_callback mail_vc = ObjCInstance(controller) mail_vc.setMailComposeDelegate_(None) mail_vc.dismissViewControllerAnimated_completion_(True, None) ObjCInstance(self).release() if dismiss_callback: dismiss_callback() try: MailDelegate = ObjCClass('MailDelegate') except ValueError: MailDelegate = create_objc_class( 'MailDelegate', superclass=NSObject, methods=[mailComposeController_didFinishWithResult_error_], protocols=['MFMailComposeViewControllerDelegate']) objc_util.retain.append( mailComposeController_didFinishWithResult_error_) MFMailComposeViewController = ObjCClass('MFMailComposeViewController') mail_vc = MFMailComposeViewController.alloc().init().autorelease() delegate = MailDelegate.alloc().init().autorelease() objc_util.retain.append(delegate) mail_vc.setMailComposeDelegate_(delegate) # Find a view controller which is not already presenting, see # https://forum.omz-software.com/topic/2060/presenting-viewcontroller/2 root_vc = UIApplication.sharedApplication().keyWindow().rootViewController( ) while root_vc.presentedViewController(): root_vc = root_vc.presentedViewController() mail_vc.setSubject_(subject) if recipients is not None: mail_vc.setToRecipients_(recipients) mail_vc.setMessageBody_isHTML_(body, body.startswith('<html>')) if filename and os.path.exists(filename): mail_vc.addAttachmentData_mimeType_fileName_( NSData.dataWithContentsOfFile_(os.path.abspath(filename)), mime_type, filename) root_vc.presentViewController_animated_completion_(mail_vc, True, None)
language = ['en'] image = None if selection == 1: image = photos.capture_image() elif selection == 2: image = photos.pick_asset().get_image() if image is not None: print('Recognizing text...\n') buffer = io.BytesIO() image.save(buffer, format='PNG') image_data = buffer.getvalue() req = VNRecognizeTextRequest.alloc().init().autorelease() req.setRecognitionLanguages_(language) handler = VNImageRequestHandler.alloc().initWithData_options_( image_data, None).autorelease() success = handler.performRequests_error_([req], None) if success: for result in req.results(): print(result.text()) else: print('Problem recognizing text') print('\n--program complete--')
from objc_util import ObjCClass, uiimage_to_png, nsurl import dialogs import ui UIImage = ObjCClass('UIImage') def get_symbols(assets_list): symbols = [] for symbol in assets_list: ins = UIImage.systemImageNamed_(symbol) if ins: png = uiimage_to_png(ins) data = {'title': str(symbol), 'image': ui.Image.from_data(png)} else: data = {'title': str(symbol)} symbols.append(data) return symbols NSBundle = ObjCClass("NSBundle") CUICatalog = ObjCClass('CUICatalog') path = NSBundle.bundleWithPath_( '/System/Library/CoreServices/CoreGlyphs.bundle').bundlePath() sf_assets = CUICatalog.alloc().initWithURL_error_( nsurl(str(path) + '/Assets.car'), None) assets_list = sf_assets.allImageNames() dialogs.list_dialog(items=get_symbols(assets_list))
from objc_util import ObjCClass, ObjCBlock, c_void_p, ns, ObjCInstance def getData(_cmd, pedometerData, error): ped = ObjCInstance(pedometerData) if not error == None: err = ObjCInstance(error) print('error====' + str(err)) else: print('Steps====' + str(ped.numberOfSteps())) print('Distance====' + str(ped.distance())) ped_block = ObjCBlock(getData, restype=None, argtypes=[c_void_p, c_void_p, c_void_p]) CMPedometer = ObjCClass('CMPedometer') NSDate = ObjCClass('NSDate') ped = CMPedometer.alloc().init() if CMPedometer.isStepCountingAvailable(): fromDate = NSDate.dateWithTimeIntervalSinceNow_(-60 * 60 * 24 * 2) toDate = NSDate.dateWithTimeIntervalSinceNow_(-60 * 60 * 24 * 1) ped.queryPedometerDataFromDate_toDate_withHandler_(ns(fromDate), ns(toDate), ped_block) else: print('Unavailable')
# https://forum.omz-software.com/topic/3016/access-to-apple-standard-language-dictionaries/11 from objc_util import ObjCClass, UIApplication, CGSize, on_main_thread, ObjCInstance import sys import ui UIReferenceLibraryViewController = ObjCClass( 'UIReferenceLibraryViewController') back = ui.View() back.background_color = 'gray' back.name = 'Dictionary' back.present('full_screen', hide_title_bar=False) input = 'word' referenceViewController = UIReferenceLibraryViewController.alloc( ).initWithTerm_(input) ObjCInstance(back).addSubview_(referenceViewController) # ObjCInstance(back).addSubview_(referenceViewController.view()) rootVC = UIApplication.sharedApplication().keyWindow().rootViewController() tabVC = rootVC.detailViewController() referenceViewController.setTitle_('Definition: {0}{1}{0}'.format('\'', input)) referenceViewController.setPreferredContentSize_(CGSize(540, 540)) referenceViewController.setModalPresentationStyle_(2) #tabVC.addTabWithViewController_(referenceViewController) tabVC.presentViewController_animated_completion_(referenceViewController, True, None)
# https://forum.omz-software.com/topic/4239/clearing-webview-cache/2 from objc_util import ObjCClass NSURLCache = ObjCClass('NSURLCache') shared_cache = NSURLCache.alloc( ).initWithMemoryCapacity_diskCapacity_diskPath_(0, 0, None) NSURLCache.setSharedURLCache_(shared_cache)