Explore the various UI frameworks available for building app interfaces. Discuss the use cases for different frameworks, share best practices, and get help with specific framework-related questions.

All subtopics
Posts under UI Frameworks topic

Post

Replies

Boosts

Views

Activity

iOS18 UINavigationBar Crash
I encountered a crash when calling the tabBarView:didSelectIndex: method, and it only happens on iOS 18. Here is crash report: `OS Version: iPhone OS 18.0.1 (22A3370) Report Version: 105 SDK Version: 0.0.4 Exception Type: SIGABRT Exception Codes: #0 at 0x1f0acb274 Crashed Thread: 0 Application Specific Information: *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Layout requested for visible navigation bar, <UINavigationBar: 0x11266ef80; frame = (0 -91; 428 44); autoresize = W; tintColor = UIExtendedSRGBColorSpace 1 1 1 0.8; layer = <CALayer: 0x301e14800>> delegate=0x112670600 standardAppearance=0x3035b3720 scrollEdgeAppearance=0x3035b3b10, when the top item belongs to a different navigation bar. topItem = <UINavigationItem: 0x14309cf00> title='' titleView=0x15b1af700 style=navigator leftBarButtonItems=0x301c08940 rightBarButtonItems=0x301caa180, navigation bar = <UINavigationBar: 0x11266e080; frame = (0 -91; 428 44); autoresize = W; tintColor = UIExtendedSRGBColorSpace 1 1 1 0.8; layer = <CALayer: 0x301e1d0a0>> delegate=0x112670000 standardAppearance=0x30355ae60 scrollEdgeAppearance=0x30355aed0, possibly from a client attempt to nest wrapped navigation controllers.' Last Exception Backtrace: 0 CoreFoundation 0x00000001a0cad08c 0x1a0c29000 + 540812 1 libobjc.A.dylib 0x000000019dfaf2e4 0x19df98000 + 94948 2 Foundation 0x00000001a007e15c 0x19f85c000 + 8528220 3 UIKitCore 0x00000001a36b6028 0x1a33f4000 + 2891816 4 UIKitCore 0x00000001a3404248 0x1a33f4000 + 66120 5 UIKitCore 0x00000001a354d878 0x1a33f4000 + 1415288 6 QuartzCore 0x00000001a2749630 0x1a26d1000 + 493104 7 UIKitCore 0x00000001a3447cd0 0x1a33f4000 + 343248 8 UIKitCore 0x00000001a34e9a60 0x1a33f4000 + 1006176 9 UIKitCore 0x00000001a354aa48 0x1a33f4000 + 1403464 10 UIKitCore 0x00000001a34f1c64 0x1a33f4000 + 1039460 11 UIKitCore 0x00000001a368e2c8 0x1a33f4000 + 2728648 12 UIKitCore 0x00000001a368c504 0x1a33f4000 + 2721028 13 UIKitCore 0x00000001a34193c8 0x1a33f4000 + 152520 14 UIKitCore 0x00000001a34191f4 0x1a33f4000 + 152052 15 UIKitCore 0x00000001a340ae84 0x1a33f4000 + 93828 16 CoreAutoLayout 0x00000001c3ad7030 0x1c3ac5000 + 73776 17 UIKitCore 0x00000001a340ddc8 0x1a33f4000 + 105928 18 UIKitCore 0x00000001a340c7f0 0x1a33f4000 + 100336 19 UIKitCore 0x00000001a378087c 0x1a33f4000 + 3721340 20 UIKitCore 0x00000001a37804f0 0x1a33f4000 + 3720432 21 UIKitCore 0x00000001a377e814 0x1a33f4000 + 3713044 22 UIKitCore 0x00000001a37ee8a4 0x1a33f4000 + 4171940 23 UIKitCore 0x00000001a37edf14 0x1a33f4000 + 4169492`
Topic: UI Frameworks SubTopic: UIKit
0
0
393
Oct ’24
IOS Status bar is missing in the screenshot
I'm using React Native to create a mobile application.When I click on a button in my app, I need to programmatically take a screenshot of the current page of my application together with the iPhone status bar that shows the time, cellular provider, and battery level. However, my app page is being captured without having the statusbar. My 'screenshot taken' function is written in Objective-C. Is this happening because of any privacy-related concerns? Would you kindly assist me with this? Attaching the screenshot code, #import <UIKit/UIKit.h> #import <React/RCTBridgeModule.h> #import <React/RCTLog.h> @interface ScreenshotModule : NSObject @end @implementation ScreenshotModule RCT_EXPORT_MODULE(); RCT_REMAP_METHOD(takeStatusBarScreenshot, resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) { dispatch_async(dispatch_get_main_queue(), ^{ @try { // Get the status bar window UIWindow *statusBarWindow = [UIApplication sharedApplication].windows.firstObject; UIScene *scene = [UIApplication sharedApplication].connectedScenes.allObjects.firstObject; if ([scene isKindOfClass:[UIWindowScene class]]) { UIWindowScene *windowScene = (UIWindowScene *)scene; BOOL statusBarHidden = windowScene.statusBarManager.isStatusBarHidden; if (statusBarHidden) { NSLog(@"Status bar is hidden, app is in full-screen mode."); } else { NSLog(@"Status bar is visible."); } } else { NSLog(@"The scene is not a UIWindowScene."); } // Check if the statusBarWindow is valid if (!statusBarWindow) { reject(@"screenshot_failed", @"Status bar window not found", nil); return; } // Get the window scene and status bar frame UIWindowScene *windowScene = statusBarWindow.windowScene; CGRect statusBarFrame = windowScene.statusBarManager.statusBarFrame; // Log the status bar frame for debugging RCTLogInfo(@"Status Bar Frame: %@", NSStringFromCGRect(statusBarFrame)); // Check if the status bar frame is valid if (CGRectIsEmpty(statusBarFrame)) { reject(@"screenshot_failed", @"Status bar frame is empty", nil); return; } // Start capturing the status bar UIGraphicsBeginImageContextWithOptions(statusBarFrame.size, NO, [UIScreen mainScreen].scale); CGContextRef context = UIGraphicsGetCurrentContext(); // Render the status bar layer [statusBarWindow.layer renderInContext:context]; // Create an image from the current context UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); if (!image) { reject(@"screenshot_failed", @"Failed to capture screenshot", nil); return; } // Convert the image to PNG format and then to a base64 string NSData *imageData = UIImagePNGRepresentation(image); if (imageData == nil) { reject(@"screenshot_failed", @"Image data is nil", nil); return; } NSString *base64String = [imageData base64EncodedStringWithOptions:0]; // Log base64 string length for debugging RCTLogInfo(@"Base64 Image Length: %lu", (unsigned long)[base64String length]); // Optionally, save the image to a file (for debugging purposes) NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"statusbar_screenshot.png"]; [UIImagePNGRepresentation(image) writeToFile:path atomically:YES]; RCTLogInfo(@"Status bar screenshot saved to: %@", path); // Resolve with the base64 image resolve(base64String); } @catch (NSException *exception) { reject(@"screenshot_error", @"Error while capturing status bar screenshot", nil); } }); } @end
Topic: UI Frameworks SubTopic: General
0
0
432
Oct ’24
Tinted widgets have an inset background in the widget gallery only
When the home screen is in tinted mode in iOS 18, the widget gallery seems to display widgets with the background inset from the edge of the widget (i.e. negative padding). You can see this behavior in the Apple News widget too, where the full-bleed content outside of the inset is very light. This only happens in the sample gallery, not when the widgets are placed on the home screen. For my widgets, this outer edge contains important content and the clipping behavior makes the widgets look poorly designed when viewed in the gallery. Is there any way to turn this behavior off and just show the widget normally in the gallery with no weird inset — the way it will actually display when added to the home screen? If it matters, my widgets are currently configured with: .contentMarginsDisabled() .containerBackground(for: .widget) { // ... (background color) */ }
2
0
470
Oct ’24
PHPickerResult slow loading, plus no thumbnails
A very common use case in our iOS app is that users take a large number of pictures (about 30) in low-light conditions using the camera app, and immediately after, they try to upload them to our servers. We measured the time to load photos from the PHPickerResult. For most photos, it takes less than 100 milliseconds, but for some of them, it takes several seconds—we even saw minutes in some extreme cases. We believe this started happening with iOS 17, when deferred photo processing was introduced. If users take the pictures using our in-app camera experience, the options to customize the camera are enough to avoid the long waiting times. However, the majority of our users still prefer to take the photos with the camera app, and there is little we can do about that. In the past few weeks, we tried many combinations: Without asking for permissions, we tried loadFileRepresentation, loadData, and loadObject. We explored the PHImageManager route, asking permissions and with different options for deliveryMode, resizeMode, version, isSynchronous, and allowSecondaryDegradedImage. We also tried fetching the photos in parallel, with very bad results. In summary, nothing helped the long waiting times—minutes in some cases. The first question is then, is there anything we can do to ignore the post-processing of the photos and get them fast? We could accept the unprocessed images. At a minimum, we would like to show our users what we are doing and why we are taking so much time. We tried to load thumbnails with loadPreviewImage and put a progress indicator on top. This method consistently gives us an error for all photos: (lldb) p error.localizedDescription (String) "Cannot load preview." We can load thumbnails with the PHImageManager option, but it seems excessive to need to get permissions only for that. Second question would be then, what can we do to load thumbnails without asking for permission? I created a feedback report with a video and sample code to reproduce -> FB15493683
2
0
491
Oct ’24
iOS App is crashing
My iOS app crashes, when kept idle in the background for sometime. Below is the detailed crash report. Incident Identifier: 90DF0404-7A1D-4AF3-8892-19AB744DF0FD Distributor ID: com.apple.AppStore Hardware Model: iPhone13,3 Process: Runner [35073] Path: /private/var/containers/Bundle/Application/894B2440-D20C-4C01-B278-A0DC4B199530/Runner.app/Runner Identifier: com.era.tk Version: 5.0.2 (5) AppStoreTools: 15F31e AppVariant: 1:iPhone13,3:15 Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] Coalition: com.era.tk [793] Date/Time: 2024-09-25 13:17:31.3101 +0100 Launch Time: 2024-09-25 12:29:23.1866 +0100 OS Version: iPhone OS 17.6.1 (21G93) Release Type: User Baseband Version: 4.70.01 Report Version: 104 Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x0000000100c75e48 Termination Reason: SIGNAL 5 Trace/BPT trap: 5 Terminating Process: exc handler [35073] Triggered by Thread: 0 Thread 0 Crashed: 0 Runner 0x0000000100c75e48 0x100c2c000 + 302664 1 Runner 0x0000000100c75e80 0x100c2c000 + 302720 2 UIKitCore 0x00000001a7e937e8 -[UIViewController _setViewAppearState:isAnimating:] + 1224 (UIViewController.m:6441) 3 UIKitCore 0x00000001a80520b0 -[UIViewController __viewWillDisappear:] + 108 (UIViewController.m:6705) 4 UIKitCore 0x00000001a8602cec -[UINavigationController _startCustomTransition:] + 1476 (UINavigationController.m:2260) 5 UIKitCore 0x00000001a7e97400 -[UINavigationController _startDeferredTransitionIfNeeded:] + 496 (UINavigationController.m:8062) 6 UIKitCore 0x00000001a7efc248 -[UINavigationController __viewWillLayoutSubviews] + 96 (UINavigationController.m:8369) 7 UIKitCore 0x00000001a81be688 -[UILayoutContainerView layoutSubviews] + 172 (UILayoutContainerView.m:89) 8 UIKitCore 0x00000001a7da7918 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1528 (UIView.m:20054) 9 QuartzCore 0x00000001a720626c CA::Layer::layout_if_needed(CA::Transaction*) + 504 (CALayer.mm:10816) 10 QuartzCore 0x00000001a7205df0 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 148 (CALayer.mm:2598) 11 QuartzCore 0x00000001a7260fd8 CA::Context::commit_transaction(CA::Transaction*, double, double*) + 464 (CAContextInternal.mm:2760) 12 QuartzCore 0x00000001a71d5ee0 CA::Transaction::commit() + 648 (CATransactionInternal.mm:432) 13 QuartzCore 0x00000001a721fc34 CA::Transaction::flush_as_runloop_observer(bool) + 88 (CATransactionInternal.mm:942) 14 UIKitCore 0x00000001a7e50ee8 _UIApplicationFlushCATransaction + 52 (UIApplication.m:3181) 15 UIKitCore 0x00000001a7e4e660 _UIUpdateSequenceRun + 84 (_UIUpdateSequence.mm:119) 16 UIKitCore 0x00000001a7e4e2a4 schedulerStepScheduledMainSection + 172 (_UIUpdateScheduler.m:1058) 17 UIKitCore 0x00000001a7e4f148 runloopSourceCallback + 92 (_UIUpdateScheduler.m:1221) 18 CoreFoundation 0x00000001a5b6b834 CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 28 (CFRunLoop.c:1957) 19 CoreFoundation 0x00000001a5b6b7c8 __CFRunLoopDoSource0 + 176 (CFRunLoop.c:2001) 20 CoreFoundation 0x00000001a5b69298 __CFRunLoopDoSources0 + 244 (CFRunLoop.c:2038) 21 CoreFoundation 0x00000001a5b68484 __CFRunLoopRun + 828 (CFRunLoop.c:2955) 22 CoreFoundation 0x00000001a5b67cd8 CFRunLoopRunSpecific + 608 (CFRunLoop.c:3420) 23 GraphicsServices 0x00000001ea5b51a8 GSEventRunModal + 164 (GSEvent.c:2196) 24 UIKitCore 0x00000001a81a1ae8 -[UIApplication _run] + 888 (UIApplication.m:3713) 25 UIKitCore 0x00000001a8255d98 UIApplicationMain + 340 (UIApplication.m:5303) 26 Runner 0x0000000100c4e660 0x100c2c000 + 140896 27 dyld 0x00000001c933f154 start + 2356 (dyldMain.cpp:1298)
Topic: UI Frameworks SubTopic: UIKit
1
0
306
Sep ’24
In PKCanvasview of IOS18, UIPanGestureRecognizer cannot be added
I am creating an application using PKCanvasview. One function of that app is the ability to trace and retrieve a UITextView that has been addSubviewed to a PKCanvasView. We have confirmed that this functionality works correctly in the simulator and on the actual device on IOS 17.4. This feature did not work correctly on the IOS18 simulator and the actual device. Is this a bug? And if it is normal behavior, is there an alternative?
0
0
438
Oct ’24
Core Data : about newBackgroundContext()
Hi everyone, I’m wondering about Core Data. When creating a private context using newBackgroundContext(), does it automatically set the parent to the view context, or is it independent? I'd appreciate it if anyone could clarify this for me. Thanks in advance! 😊
0
0
274
Sep ’24
Crashes in PHPickerViewController PFAssertionPolicyAbort
Hello! I'm getting crash reports in PHPickerViewController for iOS 17 users only. Can someone point me into the right direction what could be the root cause in my case since it's related to PHPickerViewController? Thread 0 name: Thread 0 Crashed: 0 libsystem_kernel.dylib 0x00000001e7e9342c __pthread_kill + 8 (:-1) 1 libsystem_pthread.dylib 0x00000001fbc32c0c pthread_kill + 268 (pthread.c:1721) 2 libsystem_c.dylib 0x00000001a6d36ba0 abort + 180 (abort.c:118) 3 PhotoFoundation 0x00000001d2420280 -[PFAssertionPolicyAbort notifyAssertion:] + 68 (PFAssert.m:432) 4 PhotoFoundation 0x00000001d2420068 -[PFAssertionPolicyComposite notifyAssertion:] + 160 (PFAssert.m:259) 5 PhotoFoundation 0x00000001d242061c -[PFAssertionPolicyUnique notifyAssertion:] + 176 (PFAssert.m:292) 6 PhotoFoundation 0x00000001d241f7f4 -[PFAssertionHandler handleFailureInFunction:file:lineNumber:description:arguments:] + 140 (PFAssert.m:169) 7 PhotoFoundation 0x00000001d2420c74 _PFAssertFailHandler + 148 (PFAssert.m:127) 8 PhotosUI 0x0000000216b59e30 -[PHPickerViewController _handleRemoteViewControllerConnection:extension:extensionRequestIdentifier:error:completionHandler:] + 1356 (PHPicker.m:1502) 9 PhotosUI 0x0000000216b5a954 __66-[PHPickerViewController _setupExtension:error:completionHandler:]_block_invoke_3 + 52 (PHPicker.m:1454) Crash report: 2024-09-05_18-27-56.7526_+0500-a953eaee085338a690ac1604a78de86e3e49d182.crash
2
0
560
Oct ’24
What is ChronoKit.InteractiveWidgetActionRunner.Errors Code 1?
This is a follow up to this post about building a Control Center widget to open the app directly to a particular feature. I have it working in a sample app, but when I do the same thing in my full app I get this error: [[com.olivetree.BR-Free::com.olivetree.BR-Free.VerseWidget:com.olivetree.BR-Free.ContinueReadingPlanControl:-]] Control action: failed with error: Error Domain=ChronoKit.InteractiveWidgetActionRunner.Errors Code=1 "(null)" Google has nothing for any of that. Can anyone shed light on what it means? This is my control and its action: @available(iOS 18.0, *) struct ContinueReadingPlanControl : ControlWidget { var body: some ControlWidgetConfiguration { StaticControlConfiguration(kind: "com.olivetree.BR-Free.ContinueReadingPlanControl") { ControlWidgetButton(action: ContinueReadingPlanIntent()) { Image(systemName: "book") } } .displayName("Continue Reading Plan") } } @available(iOS 18.0, *) struct ContinueReadingPlanIntent : ControlConfigurationIntent { static let title: LocalizedStringResource = "Continue Reading Plan" static let description = IntentDescription(stringLiteral: "Continue the last-used reading plan") static let isDiscoverable = false static let opensAppWhenRun: Bool = true @MainActor func perform() async throws -> some IntentResult & OpensIntent { let strUrl = "olivetree://startplanday" UserDefaults.standard.setValue(strUrl, forKey: "StartupUrl") return .result(opensIntent: OpenURLIntent(URL(string: strUrl)!)) } } Note also that I'm pulling this from Console.app, streaming the logs from my device. I don't know of a way to debug a Control Center widget in Xcode, though this thread implies that it's possible.
2
0
692
Sep ’24
UICollectionView self-sizing (list height) cells
I am trying to build a UICollectionView where the rows expand / collapse (for example, where the row only has a title initially, but when tapped expands to show a text view). I'm aware I can use UIContentConfiguration to swap a SwiftUI view for the cell's contentView, but I'm trying to do this in UIKit for configurability. I have watched WWDC 22, 10068: What's new in UIKit, which made this sound easy... I am using UICollectionLayoutListConfiguration for the UICollectionViewLayout. When a cell is tapped, I update the subviews' constraints to the "expanded" state, but this just causes the subviews to expand beyond the cell height. All subviews are on cell.contentView. Calling layoutIfNeeded, invalidateIntrinsicContentSize, on cell doesn't change the cell height. I assumed all I would need to do is set collectionView.selfSizingInvalidation = .enabledIncludingConstraints, but is overriding intrinsicContentSize of the cell the only way to accomplish this?
Topic: UI Frameworks SubTopic: UIKit
0
0
410
Oct ’24
UIDeferredMenuElement on MacCatalyst: closure called only once on first menu display
Hi folks, I'm struggling with an issue on MacCatalyst. I'm using a dynamic menu that is supposed to show the current state of a setting (state = .on / .off). The UIDeferredMenuElement works great on iOS, the closure is called on each display of the (context) menu. On MacCatalyst however - where I use the menu as a submenu in the main menu - the closure is called only once on first menu display. The system seems to show a cached menu item even though I'm using UIDeferredMenuElement.uncached. Here's the relevant code: func getMenuElement() { let element = UIDeferredMenuElement.uncached { completion in let modeString = mode.myLocalizedDescription let trackingMode = <current setting> let mode = <menu item setting option> let state = trackingMode == mode ? .on : .off let action = UIAction(title: modeString, image: <image>, state: state) { _ in viewController.setUserTrackingMode(mode) } completion([action]) } return element } Any ideas how to trick the system into generating the dynamic menu item on each menu display?
1
0
462
Sep ’24
iOS 18 Control Widget Button won't open app
XCode Version 16.0 (16A242d) iPhone 12 - iOS 18 (22A3354) Macbook Air M1 - Sonoma 14.6.1 I am currently working on building Control Buttons for our app and I have consistently run into the same issue: Unknown NSError The operation couldn’t be completed. (LNActionExecutorErrorDomain error 2018.) This error can be found in the following posts: Apple Developer Forums - Post 1 Apple Developer Forums - Post 2 Apple Developer Forums - Post 3 StackOverflow - Post 4 Github - Post 5 I've tried every single solution recommended within these posts, however nothing has worked successfully so far. Additionally, I've tried the using .widgetUrl() on the Label() within the ControlWidgetButton like so: ControlWidgetButton(action: JournalControlIntent()) { Label("Open App", systemImage: "pencil.line") .widgetURL(URL(string: "app://control/page")) } But this did not work either. Using the recommended approach to open the app as seen here: https://developer.apple.com/documentation/widgetkit/creating-controls-to-perform-actions-across-the-system#Open-your-app-with-a-control simply won't work since we have a Flutter app with deep linking setup. Meaning the only option is launching either a deep link or universal link. Our URL scheme is setup correctly since it's currently working for our iOS Widgets & Shortcuts(which use widgetURL & openURL). In Post 3, the accepted answer mentions that the control file must have the Target Membership with the App and Widget Targets to work. When I try using this solution the build fails without any errors(until you run it in VSCode where there are many errors about Derived Data - Deleting the derived data doesn't fix this error) I'm wondering if I have added the Control Widget to the incorrect folder within my XCode project? Since if you use the approach of creating a Control through XCode(File > New > Target > Widget Extension > "Include Control" > Next) it creates a top level directory in the project similar to a Stickers or Watch extension. My Control Widgets currently reside in the [App] Widgets > Control Buttons > Control Button.swift. It's then added to my main widget definition(App Widget > App_Widget.swift): @main struct App_Widget: WidgetBundle { var body: some Widget { App_Widget() // works App_Widget_One() // works if #available(iOSApplicationExtension 18.0, *) { ControlButtonOne() // does not open app ControlButtonTwo() // does not open app } } } Thank you for your help and time!
1
0
1.1k
Sep ’24
UITextField Input Issue While Using Bilingual Keyboard in iOS 18
Input issues occur in the textField while using a bilingual keyboard (Korean and English). System settings: Keyboard: Bilingual (Korean & English) Project environment: Xcode >= 15.4 & iOS >= 18.0 Base localization: Korean // UITextField settings: textField.keyboardType = .decimalPad // or .phonePad self.textField.addTarget(self, action: #selector(self.textFieldEditingChanged), for: .editingChanged) @objc func textFieldEditingChanged() { self.textField.text = "\(self.textField.text!)-" } /* Input: 123456 Expected: 1-2-3-4-5-6- Result: 11111123456- */ The issue occurs when modifying the text of the textField in the editingChanged event. In the above code, a hyphen is appended to the input with each character. When typing 123456, the expected result is: Input: 1 → Result: 1- Input: 2 → Result: 1-2- … Input: 6 → Result: 1-2-3-4-5-6- However, the actual result is 11111123456-. Another example: @objc func textFieldEditingChanged() { print("before", self.textField.text!) self.textField.text = self.textField.text?.replacingOccurrences(of: "0", with: "1") print("after", self.textField.text!) } When inputting 0 1 0 sequentially, the output is: before 0 after 1 before 01 after 11 before 010 after 111 The value of "after" matches expectations, but the "before" value reverts to 0 on the next input, even though it appears as 1 on the UI. When the bilingual keyboard option is turned off or the base localization is set to something other than Korea, the issue does not occur. Could you provide information on whether this issue will be resolved in the next iOS version, or if there is a workaround?
8
0
1.6k
Oct ’24
How to share PHAsset with UIActivityViewController like Photos App?
I am building an app about photos and I want to create a photo sharing feature like Apple's Photos App. Please see Steps to Reproduce and attached project. The current share method has the following issues The file name of the shared photo changes to “FullSizeRender”. The creation and update dates of shared photos will change to the date they were edited or shared. I want to ensure that the following conditions are definitely met Share the latest edited version. The creation date should be when the original photo was first created. How can I improve the code? STEPS TO REPRODUCE class PHAssetShareManager { static func shareAssets(_ assets: [PHAsset], from viewController: UIViewController, sourceView: UIView) { let manager = PHAssetResourceManager.default() var filesToShare: [URL] = [] let group = DispatchGroup() for asset in assets { group.enter() getAssetFile(asset, resourceManager: manager) { fileURL in if let fileURL = fileURL { filesToShare.append(fileURL) } group.leave() } } group.notify(queue: .main) { self.presentShareSheet(filesToShare, from: viewController, sourceView: sourceView) } } private static func getAssetFile(_ asset: PHAsset, resourceManager: PHAssetResourceManager, completion: @escaping (URL?) -> Void) { print("getAssetFile") let resources: [PHAssetResource] switch asset.mediaType { case .image: if asset.mediaSubtypes.contains(.photoLive) { // let editedResources = PHAssetResource.assetResources(for: asset).filter { $0.type == .fullSizePairedVideo } // let originalResources = PHAssetResource.assetResources(for: asset).filter { $0.type == .pairedVideo } let editedResources = PHAssetResource.assetResources(for: asset).filter { $0.type == .fullSizePhoto } let originalResources = PHAssetResource.assetResources(for: asset).filter { $0.type == .photo } resources = editedResources.isEmpty ? originalResources : editedResources } else { let editedResources = PHAssetResource.assetResources(for: asset).filter { $0.type == .fullSizePhoto } let originalResources = PHAssetResource.assetResources(for: asset).filter { $0.type == .photo } resources = editedResources.isEmpty ? originalResources : editedResources } case .video: let editedResources = PHAssetResource.assetResources(for: asset).filter { $0.type == .fullSizeVideo } let originalResources = PHAssetResource.assetResources(for: asset).filter { $0.type == .video } resources = editedResources.isEmpty ? originalResources : editedResources default: print("Unsupported media type") completion(nil) return } guard let resource = resources.first else { print("No resource found") completion(nil) return } let fileName = resource.originalFilename let tempDirectoryURL = FileManager.default.temporaryDirectory let localURL = tempDirectoryURL.appendingPathComponent(fileName) // Delete existing files and reset cache if FileManager.default.fileExists(atPath: localURL.path) { do { try FileManager.default.removeItem(at: localURL) } catch { print("Error removing existing file: \(error)") } } let options = PHAssetResourceRequestOptions() options.isNetworkAccessAllowed = true resourceManager.writeData(for: resource, toFile: localURL, options: options) { (error) in if let error = error { print("Error writing asset data: \(error)") completion(nil) } else { completion(localURL) } } } private static func presentShareSheet(_ items: [Any], from viewController: UIViewController, sourceView: UIView) { print("presentShareSheet") let activityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil) if UIDevice.current.userInterfaceIdiom == .pad { activityViewController.popoverPresentationController?.sourceView = sourceView activityViewController.popoverPresentationController?.sourceRect = sourceView.bounds } viewController.present(activityViewController, animated: true, completion: nil) } }```
0
0
528
Oct ’24
Do update to @Observable properties have to be done on the main thread?
According to this old thread the answer is no. But I never understood why. In the old world. It was always required that you make changes to @Published properties on the main thread. In fact compiler would complain. In the main world, can you just update that in the background thread? And then SwiftUI take cares of refreshing the views on the main thread? So I guess that begs that question, why did it used to require it for @Published? Furthermore, I have recently gotten new crashes when update is done from background but I can't be sure it's related: For example I have the following, and the crash is as follows: @Observable class PlanViewModel { var stagingPlan: Plan? func savePlan() async { //some code here.... stagingPlan = nil //crash } } Is this issue potentially related to main thread? Should I do that assignment forcefully on main thread? call stack 1 call stack 2 call stack 3 I dont know how to troubleshoot this further as xcode doesnt provide me any info other than that one red line
1
0
536
Oct ’24
strange ios crash
HI i have found libsystem_kernel.dylib crash. i can't reproduce this error even this is not unrecognisable. here is stack trace Crashed: com.apple.main-thread 0 libsystem_kernel.dylib 0xaac mach_msg_trap + 8 1 libsystem_kernel.dylib 0x107c mach_msg + 72 2 CoreFoundation 0x6c88 + 368 3 CoreFoundation 0xaf90 + 1160 4 CoreFoundation 0x1e174 CFRunLoopRunSpecific + 572 5 GraphicsServices 0x1988 GSEventRunModal + 160 6 UIKitCore 0x4e5a88 + 1080 7 UIKitCore 0x27ef78 UIApplicationMain + 336 8 libTweaks.dylib 0x2a6b4 _apdecr_UIApplicationMain(int, char**, NSString*, NSString*) + 108 9 libswiftUIKit.dylib 0x27ee4 $s5UIKit17UIApplicationMainys5Int32VAD_SpySpys4Int8VGGSgSSSgAJtF + 100 10 REDDI 0x214d6c main + 4368469356 (AppDelegate.swift:4368469356) 11 ??? 0x1028a84d0 (Missing)
Topic: UI Frameworks SubTopic: UIKit Tags:
1
0
383
Sep ’24
UIDocumentBrowserViewController create new document used to work, but...
is now broken. (but definitely worked when I originally wrote my Document-based app) It's been a few years. DocumentBrowserViewController's delegate implements the following func. func documentBrowser(_ controller: UIDocumentBrowserViewController, didRequestDocumentCreationWithHandler importHandler: @escaping (URL?, UIDocumentBrowserViewController.ImportMode) -> Void) { let newDocumentURL: URL? = Bundle.main.url(forResource: "blankFile", withExtension: "trtl2") // Make sure the importHandler is always called, even if the user cancels the creation request. if newDocumentURL != nil { importHandler(newDocumentURL, .copy) } else { importHandler(nil, .none) } } When I tap the + in the DocumentBrowserView, the above delegate func is called (my breakpoint gets hit and I can step through the code) newDocumentURL is getting defined successfully and importHandler(newDocumentURL, .copy) gets called, but returns the following error: Optional(Error Domain=com.apple.DocumentManager Code=2 "No location available to save “blankFile.trtl2”." UserInfo={NSLocalizedDescription=No location available to save “blankFile.trtl2”., NSLocalizedRecoverySuggestion=Enable at least one location to be able to save documents.}) This feels like something new I need to set up in the plist, but so far haven't been able to discover what it is. perhaps I need to update something in info.plist? perhaps one of: CFBundleDocumentTypes UTExportedTypeDeclarations Any guidance appreciated. thanks :-)
Topic: UI Frameworks SubTopic: UIKit Tags:
1
0
490
Sep ’24