Objective-C

RSS for tag

Objective-C is a programming language for writing iOS, iPad OS, and macOS apps.

Posts under Objective-C tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Does URLByResolvingBookmarkData consume any resources on iOS?
My app saves the file URLs obtained from UIDocumentPickerViewController as bookmark data and reads them on the "history screen". In the "history screen", whenever viewWillAppear is called in ViewController, URLByResolveBookmarkData is called for all bookmarks to check if the file has been deleted or moved. (Please see code below) - (void)refresh { NSManagedObjectContext* context = self.managedObjectContext; // read all bookmarks NSArray<HistoryItem*>* all = [self histories]; [all enumerateObjectsUsingBlock:^(HistoryItem * _Nonnull item, NSUInteger idx, BOOL * _Nonnull stop) { BOOL isStale; NSURL* url = [NSURL URLByResolvingBookmarkData: item.bookmark options: 0 relativeToURL: nil bookmarkDataIsStale: &isStale error: nil]; if(url == nil) { // file is deleted [context deleteObject: item]; } else { item.filename = url.lastPathComponent; if(isStale) { // file is moved NSData *data = [url bookmarkDataWithOptions: 0 includingResourceValuesForKeys: 0 relativeToURL: nil error: nil]; if(data != nil) { item.bookmark = data; } } } }]; [context save: nil]; } Then, after many calls to viewWillAppear, calling startAccessingSecurityScopedResource on the URL obtained by URLByResolvingBookmarkData returns NO. I suspect that URLByResolveBookmarkData is consuming some resources, because the problem reproduces even if I change the code inside the block to only call URLByResolveBookmarkData, and it doesn't reproduce when I empty the block. Does URLByResolvingBookmarkData consume any resources? If so, how do I release the consumed resources? OS: iOS 15 Xcode: 15.0
3
0
336
Oct ’23
NSRunningApplication activateWithOptions does not work on Sonoma
Hello, Our application uses following code to activate itself: void BecomeFrontMostApp() { @autoreleasepool { if ([NSApp isActive] == YES) return; [[NSRunningApplication currentApplication] activateWithOptions: NSApplicationActivateIgnoringOtherApps | NSApplicationActivateAllWindows ]; } } Code works on Ventura and previous OS versions but not on Sonoma. On Sonoma application does not come to foreground but instead dock icon starts jumping same way when calling: [NSApp requestUserAttention: NSCriticalRequest]; And activateWithOptions returns false. I checked activationPolicy on the app running on Sonoma - it is NSApplicationActivationPolicyRegular Any ideas how to fix this appreciated.
2
0
486
Oct ’23
Is there a way to determine if the mouse and cursor are currently dissociated using CGAssociateMouseAndMouseCursorPosition?
This status is essential for generating simulated CGEvents. Games often use this API to implement cursor lock. If we send CGEvents with a moving position, it's possible for the cursor to move outside the game window and cause the game window to become inactive. If we don't send CGEvents with updated positions, we can only control the mouse within the game but not in other windows or the desktop.
0
0
400
Oct ’23
'kUTTypeJPEG' is deprecated: first deprecated in macOS 12.0 - Use UTTypeJPEG
Updating to MacOS 12, in Objective C, I get the above warning regarding changing kUTTypeJPEG to UTTypeJPEG in two places The old code still works but even after the @import UniformTypeIdentifiers changing kUTTypeJPEG to UTTypeJPEG with various types, e.g. CFString, CFStringRef, and that UTTYPE doesn't bridge???, etc. (I am obviously clueless about this) I get the compiler warnings to go away but then the program crashes. How do I fix these? Something to do with ARC or bridging??? CGImageDestinationRef destinationRef = CGImageDestinationCreateWithURL((__bridge CFURLRef)theURL, (NSString *)kUTTypeJPEG, 1, NULL); NSDictionary *imageSourceCreationOptions = [NSDictionary dictionaryWithObjectsAndKeys: kUTTypeJPEG,(NSString *)kCGImageSourceTypeIdentifierHint, (NSNumber *)kCFBooleanTrue, (NSString *)kCGImageSourceShouldCache, (NSNumber *)kCFBooleanTrue, (NSString *)kCGImageSourceShouldAllowFloat, nil];
2
0
767
Oct ’23
Using VoiceOver's accessibilityCustomActions and supporting Voice Control for the group subviews
Hi, My app supports VoiceOver and VoiceControl, and I find it hard or perhaps even impossible to support both when it comes to grouping accessibility elements. I have an element containing multiple subviews, and I want to define it as a group of accessibility custom actions to enhance VoiceOver navigation. (So that the user can focus on the entire element, and just swipe up or down if they want to activate one of its subviews as a custom action). To do that, I'm setting isAccessibilityElement to YES and I'm using accessibilityCustomActions where I create a custom action for each of this element's subviews. This works fine and presents the accessibility custom actions as expected. The struggle comes when I try to combine it with Voice Control. Since the element contains multiple subviews, I want each of these subviews to be accessible when using Voice Control with item numbers, for example. Instead, Voice Control is setting a number only on the entire element, ignoring its subviews. This is not functional because each of these subviews performs a different action when activating it. I found that VoiceControl is only numbering subviews when the parent's isAccessibilityElement is set to NO. And indeed, when changing to NO, the subviews are getting numbered, but the custom actions group break, and VoiceOver treats each element as a separate accessibility element. So I can't use accessibilityCustomActions AND supporting VoiceControl. Is this an intended behavior defined by Apple? Or, is there anyway I can support them both?
0
0
367
Oct ’23
iOS17, _UIGraphicsBeginImageContextWithOptions crash, how should solve?
Incident Identifier: C7E20EA3-7315-404A-83D5-8DBD20F8406B Hardware Model: iPad13,1 Process: 月儿记账 [352] Path: /private/var/containers/Bundle/Application/1F4F62A3-A990-4094-9982-DB0CFBB82662/月儿记账.app/月儿记账 Identifier: top.bytearts.money Version: 1.6.0 (000194) AppStoreTools: 15A240a AppVariant: 1:iPad13,1:15 Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] Coalition: top.bytearts.money [491] Date/Time: 2023-09-28 00:34:09.5371 +0800 Launch Time: 2023-09-28 00:34:03.1161 +0800 OS Version: iPhone OS 17.0 (21A329) Release Type: User Report Version: 104 Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: SIGNAL 6 Abort trap: 6 Terminating Process: 月儿记账 [352] Triggered by Thread: 0 Last Exception Backtrace: 0 CoreFoundation 0x19862a5e0 __exceptionPreprocess + 164 (NSException.m:249) 1 libobjc.A.dylib 0x1909abc00 objc_exception_throw + 60 (objc-exception.mm:356) 2 Foundation 0x197b944d4 -[NSAssertionHandler handleFailureInFunction:file:lineNumber:description:] + 172 (NSException.m:261) 3 UIKitCore 0x19a844904 _UIGraphicsBeginImageContextWithOptions + 568 (UIGraphics.m:407) 4 UIKitCore 0x19a8428d0 -[UIImageView(Pretiling) _updatePretiledImageCacheForImage:] + 812 (UIImageView_Pretiling.m:171) 5 UIKitCore 0x19a7920b0 -[UIImageView _updateImageViewForOldImage:newImage:] + 496 (UIImageView.m:3604) 6 UIKitCore 0x19a75c0fc -[UIImageView _resolveImagesWithPreviouslyDisplayedImage:] + 836 (UIImageView.m:3409) 7 UIKitCore 0x19a75bd74 -[UIImageView _setImage:invalidatingPendingSymbolTransitions:] + 280 (UIImageView.m:1379) 8 UIKitCore 0x19a7c1ab0 -[UIButtonLegacyVisualProvider _updateBackgroundImageView] + 124 (UIButtonLegacyVisualProvider.m:1795) 9 UIKitCore 0x19a7c02c4 -[UIButtonLegacyVisualProvider layoutSubviews] + 100 (UIButtonLegacyVisualProvider.m:2379) 10 UIKitCore 0x19a7c021c -[UIButton layoutSubviews] + 40 (UIButton.m:2811) 11 UIKitCore 0x19a7831d8 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1528 (UIView.m:19754) 12 QuartzCore 0x199b9b888 CA::Layer::layout_if_needed(CA::Transaction*) + 500 (CALayer.mm:10783) 13 QuartzCore 0x199b9b410 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 144 (CALayer.mm:2594) 14 QuartzCore 0x199ba194c CA::Context::commit_transaction(CA::Transaction*, double, double*) + 464 (CAContextInternal.mm:2792) 15 QuartzCore 0x199b9ac3c CA::Transaction::commit() + 648 (CATransactionInternal.mm:432) 16 QuartzCore 0x199b9a8e4 CA::Transaction::flush_as_runloop_observer(bool) + 88 (CATransactionInternal.mm:942) 17 CoreFoundation 0x1985731dc __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 36 (CFRunLoop.c:1789) 18 CoreFoundation 0x198571be4 __CFRunLoopDoObservers + 548 (CFRunLoop.c:1902) 19 CoreFoundation 0x198571300 __CFRunLoopRun + 1028 (CFRunLoop.c:2983) 20 CoreFoundation 0x198570e18 CFRunLoopRunSpecific + 608 (CFRunLoop.c:3420) 21 GraphicsServices 0x1db02d5ec GSEventRunModal + 164 (GSEvent.c:2196) 22 UIKitCore 0x19a97f350 -[UIApplication _run] + 888 (UIApplication.m:3690) 23 UIKitCore 0x19a97e98c UIApplicationMain + 340 (UIApplication.m:5275) 24 月儿记账 0x10067cfcc main + 68 (main.m:18) 25 dyld 0x1bad53d44 start + 2104 (dyldMain.cpp:1269)
3
1
746
Oct ’23
How to store the userdata in system keychain instead of Default keychains
I need to store some data of my application in system keychain which should to accessible to all the users in the system. Here is the below sample code : // Create a SecAccessControlRef for a keychain item with access control SecAccessControlRef accessControl = SecAccessControlCreateWithFlags( kCFAllocatorDefault, kSecAttrAccessibleWhenUnlocked, kSecAccessControlUserPresence, NULL ); // Define a query dictionary for a keychain item NSDictionary *query = @{ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword, (__bridge id)kSecAttrService: @"MyService", (__bridge id)kSecAttrAccount: @"MyAccount", (__bridge id)kSecValueData: [@"MyPassword" dataUsingEncoding:NSUTF8StringEncoding], (__bridge id)kSecAttrAccessControl: (__bridge_transfer id)accessControl, }; // Add the keychain item to the default keychain (login keychain) OSStatus status = SecItemAdd((__bridge CFDictionaryRef)query, NULL); if (status != errSecSuccess) { NSLog(@"Error adding keychain item: %d", (int)status); } I tried using SecKeychainOpen to access the system keychain but SecKeychainOpen is deprecated and I could not find any equivalent latest API to support that. SecKeychainRef systemKeychain; OSStatus status = SecKeychainOpen("/Library/Keychains/System.keychain", &systemKeychain); if (status != errSecSuccess) { NSLog(@"Error opening system keychain: %d", status); } else { SecAccessControlRef accessControl = SecAccessControlCreateWithFlags( kCFAllocatorDefault, kSecAttrAccessibleWhenUnlocked, kSecAccessControlUserPresence, NULL ); NSDictionary *query = @{ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword, (__bridge id)kSecAttrService: @"MyService", (__bridge id)kSecAttrAccount: @"MyAccount", (__bridge id)kSecValueData: [@"MyPassword" dataUsingEncoding:NSUTF8StringEncoding], (__bridge id)kSecUseKeychain: (__bridge id)systemKeychain, (__bridge id)kSecAttrAccessControl: (__bridge_transfer id)accessControl, }; // Add the keychain item to the system keychain status = SecItemAdd((__bridge CFDictionaryRef)query, NULL); if (status != errSecSuccess) { NSLog(@"Error adding keychain item to system keychain: %d", (int)status); } if (systemKeychain) { CFRelease(systemKeychain); } } ANY suggestions will be helpful, Please help!
3
0
500
Oct ’23
Xcode 14.3/15.0 Always Regenerates Objective-C Header from Swift Modules
Hi all, Our Objective-C project has quite a few Swift submodule that are linked with static Mach-O. The submodules are built and used in Objective-C files (.m, .mm) using the syntax #import <MyModule/MyModule-Swift.h> Since Xcode 14.3 and the early versions of Xcode 15.0, whenever I make any code changes in the .m .mm files (even just a space), all files using the Swift submodules are rebuilt. During my checks, I noticed the generated header of the submodules (MyModule-Swift.h) is regenerated even when its content hasn't changed. The modification time of the header file leads to the rebuilding of all Objective-C files. Of course, our project has a clean build when importing *-Swift.h in the .pch file, sometimes errors are thrown due to header changes during the build process. This behavior was not present in Xcode 14.2. More info I've tried configuring some flags in the Build settings, but they didn't work. Does anyone have any solutions to suggest for fixing this issue and saving our project ? :( Thanks!
1
0
452
Oct ’23
UIKit Live Preview for Objective-C View Controller?
Now that live previews are available in UIKit (source: https://developer.apple.com/wwdc23/10252) I was wondering how to get a UIViewController from Objective-C. The Swift macro looks like this: #Preview { var controller = SomeViewController() return controller; } Is there a way to get a live preview for UIViewControllers/UIViews written in Objective-C (other than wrapping it as a child view controller in an empty swift view controller)?
4
0
882
Sep ’23
iOS SDK Objective-C Audio Route Change
I'm trying to simply set my audio to the iPhone earpiece. No success, this seems like it would work. Using iOS 17 on an iPhone 15 Pro. It doesn't throw any errors. Any advice appreciated. @implementation AudioTogglePlugin - (void)setAudioMode:(CDVInvokedUrlCommand *)command { NSLog(@"... audiotoggle test ..."); NSError* err; AVAudioSession *session = [AVAudioSession sharedInstance]; [session setCategory:AVAudioSessionCategoryPlayAndRecord mode:AVAudioSessionModeVoiceChat options:AVAudioSessionCategoryOptionMixWithOthers error:NULL]; [session overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:&err]; [session setActive:YES error:NULL]; NSLog(@"... audiotoggle error ... %@", err); NSLog(@"... audiotoggle route ... %@", [session currentRoute]); } @end The audio route stays on "Speaker": inputs = ( "<AVAudioSessionPortDescription: 0x283ae0d50, type = MicrophoneBuiltIn; name = iPhone Microphone; UID = Built-In Microphone; selectedDataSource = Front>" ); outputs = ( "<AVAudioSessionPortDescription: 0x283ae0dd0, type = Speaker; name = Speaker; UID = Speaker; selectedDataSource = (null)>" )>
0
0
500
Sep ’23
PDFKit page render issue
Hi there, I am currently facing an issue with PDFKit page rendering. In one of my application, I have to open annoted PDF for reading and when user tap on particular annotation, I have to jump certain number of pages in same PDF to open the new desired page. Example: User is on page 2 and when user tap on menu button, I need to navigate directly on page number 8. With above scenario, my application takes a while to load page number 8 and User can see white screen before loading PDF page. When I checked console log, I can see following as an error. F.I: App requires to use usePageViewController for pagination. I am using as per following: _pdfView = [[PDFView alloc] initWithFrame:[UIScreen mainScreen].bounds]; [view addSubview:self.pdfView]; self.pdfView.delegate = self; [self.pdfView setAutoScales:true]; [self.pdfView setDisplayDirection:kPDFDisplayDirectionHorizontal]; [self.pdfView usePageViewController:true withViewOptions:nil]; [self.pdfView setBackgroundColor:UIColor.whiteColor]; Warning: Unable to complete drawing page index 24 on time as a request to forceUpdateActivePageIndex:withMaxDuration: 0.02 I hope if someone can help me on that Thanks.
0
0
548
Sep ’23
MacOS - SSID attribute is Nil on Sonoma OS version
Hi Team, I have been recently working on MacOS native application which interactes with Native API's to fetch SSID but recently this below mentioned API is returning nil as response on Sonoma OS Version. Below is the Objective - C for code reference CWWiFiClient *client = [CWWiFiClient sharedWiFiClient]; CWInterface *interface = [client interface]; NSString *ssid = [interface ssid]; I'm referring to following API - https://developer.apple.com/documentation/corewlan/cwwificlient?language=objc And trying to retrieve ssid https://developer.apple.com/documentation/corewlan/cwinterface?language=objc Note : The API is working on MacOS 13.0+ version and this seems to have broken in 14.0+ version Could you please provide us more details on the API issue, or any alternatives that can be followed, because from the documentation the above code seems to be a valid operation and nothing that is deprecated or restricted.
8
1
1.3k
Oct ’23
F2 key press event for macOS
Why kVK_F2 is not equivalent to constant NSF2FunctionKey for F2 key press event, What is equivalent constant of kVK_F2, since carbon framework is deprecated. When I printed the keyCode, The [Event keyCode] against NSF2FunctionKey is 63237(0xF705) whereas for kVK_F2, it prints is 120 which is 0x78. 0x78 seems to be the standard keyboard value for F2 key. Sample code : //@property (nonatomic, strong) id eventMonitor; NSEvent* (^handler)(NSEvent*) = ^(NSEvent *theEvent) { NSEvent *result = theEvent; NSUInteger flags = [theEvent modifierFlags] &amp; NSEventModifierFlagDeviceIndependentFlagsMask; if ((flags &amp; NSEventModifierFlagFunction) &amp;&amp; (flags &amp; NSEventModifierFlagCommand) &amp;&amp; ([theEvent keyCode] == NSF2FunctionKey)) { NSLog(@"Command + F2 key pressed."); } return result; }; _eventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:(NSEventModifierFlagFunction | NSEventMaskKeyDown) handler:handler];
1
0
455
Sep ’23
base::SequencedTaskRunnerHandle::Get crash on macOS while calling NSAccessibilityGetObjectValueForAttribute
Hello all, I have an application which retrieves URL from browser using accessibility. From time to time I am having this crash and I don't know the reason for it. Could you please help me? This is the stacktrace: It is happening on MacOS 13.5 and it happens on an application built for x86_64 and arm64
2
0
453
Sep ’23
loadFileRepresentationForTypeIdentifier returns an empty file
Calling loadFileRepresentationForTypeIdentifier sometimes returns an empty file, the URL params is filled with a path where a file exists, however it contains empty content. My app is released on the store and this error happens 1.5% of the time my users pick an image / video from their gallery using the UIImagePickerControllerDelegate. I was able to reproduce this bug and here is a screenshot of XCode in debug mode so you can see that the file is empty right after calling loadFileRepresentationForTypeIdentifier I'm using XCode 14.3.1, a real iPhone 12 with iOS 16.3.1 and coding in Objective-C. Step to repro : 1- Capture a live photo with your device 2- Pick this photo from your gallery using UIImagePickerControllerDelegate -> didFinishPicking 3- Grab the item provider and call provider loadFileRepresentationForTypeIdentifier:@"public.jpeg" 4- Inside the completion handler check the file size of the URL provided in the parameters It is 1.5% repro, so to repro in local I had to take hundreds of live photos. But with patience, it happens and you can debug. Note: Calling a second time loadFileRepresentationForTypeIdentifier:@"public.jpeg" inside the completionHandler returns a URL pointing to a real file with existing content, thus there might be some race conditions somewhere. Do you have any workarounds?
0
1
666
Sep ’23