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

UIDocumentPickerViewController Dismisses Automatically Twice When Selecting Multiple Files Quickly
Description: When using UIDocumentPickerViewController in iOS, if the user taps two or more files in quick succession, the picker view controller dismisses itself automatically twice. This results in an unintended behavior, leading to inconsistent screen states or redundant dismiss animations. Steps to Reproduce: Initialize a UIDocumentPickerViewController instance in UIDocumentPickerModeImport. UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:@[(NSString *)kUTTypeData] inMode:UIDocumentPickerModeImport]; documentPicker.delegate = self; documentPicker.modalPresentationStyle = UIModalPresentationFullScreen; documentPicker.allowsMultipleSelection = NO; [self presentViewController:documentPicker animated:YES completion:nil]; Launch the document picker. Quickly tap two or more files in succession. Expected Behavior: The UIDocumentPickerViewController should dismiss once and call the delegate method documentPicker:didPickDocumentsAtURLs: with the selected file(s). Actual Behavior: The UIDocumentPickerViewController automatically dismisses twice. This issue occurs even when no explicit call to dismissViewControllerAnimated: is made in the delegate method. Observed Results: The didPickDocumentsAtURLs: callback is invoked after the picker is already dismissed. During this process, unintended behavior such as multiple dismiss animations, view controller state corruption, or UI inconsistencies may occur. Impact: This issue disrupts the user experience and causes UI glitches when selecting documents. It prevents developers from having full control over dismiss behavior or mitigating the problem programmatically. Environment: iOS Version: iOS 15.0 and later (also reproduced on iOS 17.4) Device: Reproducible on multiple iPhone and iPad models Framework: UIKit Conclusion: This appears to be a system-level issue with UIDocumentPickerViewController. The automatic dismiss behavior is not correctlyhandling multiple taps, causing unintended dismiss events. Developers have no explicit way to prevent this behavior or gain full control over the dismissal process. We kindly request Apple to investigate and resolve this issue to ensure UIDocumentPickerViewController behaves as expected when interacting with multiple taps.
Topic: UI Frameworks SubTopic: UIKit Tags:
0
1
358
Dec ’24
Button Behavior between fullScreenCover and sheet
The behavior of the Button in ScrollView differs depending on how the View is displayed modally. When the View is displayed as a .fullScreenCover, if the button is touched and scrolled without releasing the finger, the touch event is canceled and the action of the Button is not called. On the other hand, if the View is displayed as a .sheet, the touch event is not canceled even if the view is scrolled without lifting the finger, and the action is called when the finger is released. In order to prevent accidental interaction, I feel that the behavior of .fullScreenCover is better, as it cancels the event immediately when scrolling. Can I change the behavior of .sheet? Demo movie is here: https://x.com/kenmaz/status/1896498312737611891 Sample code import SwiftUI @main struct SampleApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { @State private var showSheet = false @State private var showFullScreen = false var body: some View { VStack(spacing: 16) { Button("Sheet") { showSheet.toggle() } Button("Full screen") { showFullScreen.toggle() } } .sheet(isPresented: $showSheet) { SecondView() } .fullScreenCover(isPresented: $showFullScreen) { SecondView() } .font(.title) } } struct SecondView: View { @Environment(\.dismiss) var dismiss var body: some View { ScrollView { Button("Dismiss") { dismiss() } .buttonStyle(MyButtonStyle()) .padding(.top, 128) .font(.title) } } } private struct MyButtonStyle: ButtonStyle { func makeBody(configuration: Self.Configuration) -> some View { configuration .label .foregroundStyle(.red) .background(configuration.isPressed ? .gray : .clear) } }
Topic: UI Frameworks SubTopic: SwiftUI
0
0
181
Mar ’25
Crash on Intel during UI layout
We've got a hard to repro issue on Intel only when performing UI layout. It seems the collection view code gets into a recursive loop of doom and eventually the app crashes. This is only happening on Intel, the ARM version is fine. It seems related to this issue: https://developer.apple.com/forums/thread/732580 There an Apple Dev acknowledges that there are issues with the Intel version of the OS. Here's the simplified stack we're seeing: -[NSISEngine _coreReplaceMarker:withMarkerPlusDelta:]" -[NSISEngine constraintDidChangeSuchThatMarker:shouldBeReplacedByMarkerPlusDelta:]", -[NSISEngine tryToChangeConstraintSuchThatMarker:isReplacedByMarkerPlusDelta:undoHandler:]", -[NSLayoutConstraint _tryToChangeContainerGeometryWithUndoHandler:]", -[NSLayoutConstraint _setSymbolicConstant:constant:symbolicConstantMultiplier:]", -[NSLayoutConstraint setConstant:]", -[NSView(NSConstraintBasedLayoutInternal) _updateSimpleAutoresizingConstraintsInPlace:forAutoresizingMask:]", NSViewUpdateConstraintsForFrameChange -[NSView setFrameSize:]", -[NSView setFrame:]", -[NSClipView _updateOverhangSubviewsIfNeeded]", -[NSClipView _reflectDocumentViewFrameChange]", -[NSView _postFrameChangeNotification]"," -[NSView setFrameSize:]", -[NSCollectionView setFrameSize:]", -[NSView setFrame:]", NSViewActuallyUpdateFrameFromLayoutEngine", -[NSView resizeSubviewsWithOldSize:]", -[NSView setFrameSize:]", -[NSClipView setFrameSize:]", -[NSView setFrame:]", -[NSScrollView _setContentViewFrame:]", -[NSScrollView tile]", -[NSScrollView _tileWithoutRecursing]", -[NSScrollView reflectScrolledClipView:]", -[NSClipView _reflectDocumentViewFrameChange]_block_invoke", -[NSClipView _reflectDocumentViewFrameChange]", -[NSView _postFrameChangeNotification]", -[NSView setFrameSize:]", -[NSCollectionView setFrameSize:]", -[NSView setFrame:]", -[NSCollectionView _resizeToFitContentAndClipView]", -[_NSCollectionViewCore setContentSize:]", -[_NSCollectionViewCore _updateVisibleCellsNow:]" -[_NSCollectionViewCore _updateVisibleCellsNow:]" -[_NSCollectionViewCore _updateVisibleCellsNow:]" -[_NSCollectionViewCore _updateVisibleCellsNow:]" . . It seems to be limited to macOS 13.1 too. Hoping someone might have a clue? Thanks, Robert. Here's a link to the full stack: https://www.icloud.com/notes/076h1RXj4rvv7TzS5ICnvG6vw#NSCollectionView_crash_stack:
Topic: UI Frameworks SubTopic: AppKit
0
0
348
Dec ’24
SwiftUI Gestures prevent subview gesture when build with XCode 16 in iOS 18
I have a view with some buttons, and add 2 gestures using simultaneously. My app works well when built with XCode less than 16, or run on iOS less than 18.0. Example code is below: VStack(spacing: 0) { Button { print("button tapped") } label: { Rectangle() .foregroundColor(.red) } .frame(height: 100) } .gesture( DragGesture(minimumDistance: 0) .onEnded { value in print("single tap") } .simultaneously(with: TapGesture(count: 2).onEnded { print("double tap") } ) ) .frame(width: 200, height: 200) .border(Color.purple) I expect the action on Button should be recognized and print out button tapped, but only single tap and double tap are recognized
0
1
304
Mar ’25
How to set the ZPriority of a MapKit Annotation with SwiftUI
Am displaying a number of annotations on a map which vary their location over time and can inherently cluster together. I'd like to be able to set the Z order on the annotations as I have simple logic how to order them in the Z direction. I see the ZPriority property on UIKit Annotation view, but unclear how I can do that in SwiftUI. Is this exposed in any manner? I thought I could create a viewModifier and using the content parameter I'd be able to drop down into the UIKIt view to apply the value to the property, but alas I'm not seeing a clear way to do so. Is this at all possible without dropping down entirely to creating a NSViewRepresentable/UIViewRepresentable implementation of Map?
0
0
336
Dec ’24
Occasional PDFKit crash at PageLayout::getWordRange(unsigned long, long)
At this line of code (SketchTextSelectionManager.swift:449), sometimes there will be crashes based on crashlytics reports. let selection = pdfPage.selectionForWord(at: location) This is directly calling into PDFKit's PDFPage#selection method: https://developer.apple.com/documentation/pdfkit/pdfpage/selectionforword(at:) Attached the full stacktrace: Crashed: com.apple.root.user-initiated-qos.cooperative 0 CoreGraphics 0x30c968 PageLayout::getWordRange(unsigned long, long) const + 908 1 CoreGraphics 0x30bbc0 PageLayout::getTextRangeIndex(CGPoint, CGPDFSelectionType, SelectionPrecision) const + 2292 2 CoreGraphics 0x44a53c CGPDFSelectionCreateBetweenPointsWithOptions + 384 3 PDFKit 0x8d5f8 -[PDFPage selectionFromPoint:toPoint:type:] + 168 4 PDFKit 0x92040 -[PDFPage _rvItemAtPoint:] + 64 5 PDFKit 0x91f4c -[PDFPage rvItemAtPoint:] + 84 6 PDFKit 0x8caa8 -[PDFPage selectionForWordAtPoint:] + 40 7 MyApp 0x8420e0 closure #1 in SketchTextSelectionManager.startNewTextSelection(pageId:location:) + 449 (SketchTextSelectionManager.swift:449) 8 MyApp 0x841a70 SketchTextSelectionManager.startNewTextSelection(pageId:location:) + 205 (CurrentNoteManager.swift:205) 9 libswift_Concurrency.dylib 0x61104 swift::runJobInEstablishedExecutorContext(swift::Job*) + 252 10 libswift_Concurrency.dylib 0x63a28 (anonymous namespace)::ProcessOutOfLineJob::process(swift::Job*) + 480 11 libswift_Concurrency.dylib 0x611c4 swift::runJobInEstablishedExecutorContext(swift::Job*) + 444 12 libswift_Concurrency.dylib 0x62514 swift_job_runImpl(swift::Job*, swift::SerialExecutorRef) + 144 13 libdispatch.dylib 0x15d8c _dispatch_root_queue_drain + 392 14 libdispatch.dylib 0x16590 _dispatch_worker_thread2 + 156 15 libsystem_pthread.dylib 0x4c40 _pthread_wqthread + 228 16 libsystem_pthread.dylib 0x1488 start_wqthread + 8 ```
0
1
276
Feb ’25
Multipeer Connectivity with iOS devices
I used the Multipeer Connectivity Framework to allow players of my game app to see the highest score along with their own score as the game progresses. It works fine running in 3 or 4 simulators in Xcode. However, I was just told by two Apple support reps that bluetooth connectivity is not allowed between two Apple devices, other than for watches, AirPods, headphones, etc. My question is: can two iPhones or iPads connect for peer-to-peer play? Can they play offline? If the answer is yes to either or both of those questions, how do I get that to happen since I get an error message when trying to connect two iPhones via bluetooth even though they can see each other in the Other Devices list? If the answer is no, then why does Apple provide a Multipeer Connectivity Framework and simulate that type of device to device connection with the Xcode simulators?
Topic: UI Frameworks SubTopic: SwiftUI
0
0
168
Feb ’25
PhoneSceneDelegate white screen
I am currently implementing multiple scenes in my React Native / Swift application (one scene for the phone and one scene for CarPlay). I am facing an issue where one scene renders completely white (on the iPhone) but I can see in the console that the code is running (for example if I add a console.log to the App.tsx I can see that console log happen in XCode). There are no errors when building the app in XCode, and testing with the simulator CarPlay appears to render the correct output, but there is no component being rendered on the simulated phone screen (just white). AppDelegate.swift import CarPlay import React import React_RCTAppDelegate import ReactAppDependencyProvider import UIKit @main class AppDelegate: RCTAppDelegate { var rootView: UIView?; static var shared: AppDelegate { return UIApplication.shared.delegate as! AppDelegate } override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { self.moduleName = "appName" self.dependencyProvider = RCTAppDependencyProvider() self.initialProps = [:] self.rootView = self.createRootView( with: RCTBridge( delegate: self, launchOptions: launchOptions ), moduleName: self.moduleName!, initProps: self.initialProps! ); return super.application(application, didFinishLaunchingWithOptions: launchOptions) } override func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { if (connectingSceneSession.role == UISceneSession.Role.carTemplateApplication) { let scene = UISceneConfiguration(name: "CarPlay", sessionRole: connectingSceneSession.role) scene.delegateClass = CarSceneDelegate.self return scene } let scene = UISceneConfiguration(name: "Phone", sessionRole: connectingSceneSession.role) scene.delegateClass = PhoneSceneDelegate.self return scene } override func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {} override func sourceURL(for bridge: RCTBridge) -> URL? { self.bundleURL() } override func bundleURL() -> URL? { #if DEBUG RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index") #else Bundle.main.url(forResource: "main", withExtension: "jsbundle") #endif } } PhoneSceneDelegate.swift import Foundation import UIKit import SwiftUI class PhoneSceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow?; func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { if session.role != .windowApplication { return } guard let appDelegate = (UIApplication.shared.delegate as? AppDelegate) else { return } guard let windowScene = (scene as? UIWindowScene) else { return } let rootViewController = UIViewController() rootViewController.view = appDelegate.rootView; let window = UIWindow(windowScene: windowScene) window.rootViewController = rootViewController self.window = window window.makeKeyAndVisible() } } App.tsx import React, {useEffect, useState} from 'react'; import type {PropsWithChildren} from 'react'; import {CarPlay, ListTemplate} from 'react-native-carplay'; import { ScrollView, StatusBar, StyleSheet, Text, useColorScheme, View, } from 'react-native'; import { Colors, DebugInstructions, Header, LearnMoreLinks, ReloadInstructions, } from 'react-native/Libraries/NewAppScreen'; type SectionProps = PropsWithChildren<{ title: string; }>; function Section({children, title}: SectionProps): React.JSX.Element { const isDarkMode = useColorScheme() === 'dark'; return ( <View style={styles.sectionContainer}> <Text style={[ styles.sectionTitle, { color: isDarkMode ? Colors.white : Colors.black, }, ]}> {title} </Text> <Text style={[ styles.sectionDescription, { color: isDarkMode ? Colors.light : Colors.dark, }, ]}> {children} </Text> </View> ); } function App(): any { // React.JSX.Element const isDarkMode = useColorScheme() === 'dark'; const backgroundStyle = { backgroundColor: isDarkMode ? Colors.darker : Colors.lighter, }; const [carPlayConnected, setCarPlayConnected] = useState(CarPlay.connected); useEffect(() => { function onConnect() { setCarPlayConnected(true); CarPlay.setRootTemplate(new ListTemplate(/** This renders fine on the CarPlay side */)); } function onDisconnect() { setCarPlayConnected(false); } CarPlay.registerOnConnect(onConnect); CarPlay.registerOnDisconnect(onDisconnect); return () => { CarPlay.unregisterOnConnect(onConnect); CarPlay.unregisterOnDisconnect(onDisconnect); }; }); if (carPlayConnected) { console.log('car play connected'); } else { console.log('car play not connected'); } const safePadding = '5%'; // This doesn't render on the phone? return ( <View style={backgroundStyle}> <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} backgroundColor={backgroundStyle.backgroundColor} /> <ScrollView style={backgroundStyle}> <View style={{paddingRight: safePadding}}> <Header/> </View> <View style={{ backgroundColor: isDarkMode ? Colors.black : Colors.white, paddingHorizontal: safePadding, paddingBottom: safePadding, }}> <Section title="Step One"> Edit <Text style={styles.highlight}>App.tsx</Text> to change this screen and then come back to see your edits. </Section> <Section title="See Your Changes"> <ReloadInstructions /> </Section> <Section title="Debug"> <DebugInstructions /> </Section> <Section title="Learn More"> Read the docs to discover what to do next: </Section> <LearnMoreLinks /> </View> </ScrollView> </View> ); } const styles = StyleSheet.create({ sectionContainer: { marginTop: 32, paddingHorizontal: 24, }, sectionTitle: { fontSize: 24, fontWeight: '600', }, sectionDescription: { marginTop: 8, fontSize: 18, fontWeight: '400', }, highlight: { fontWeight: '700', }, }); export default App; I have been attempting to get this working now for some 20+ hours with no luck with searching for answers elsewhere. I am very new to building apps with React Native and Swift so could do with some support.
0
0
314
Mar ’25
Button in navigation bar using UIHostingController appears after push animation
I'm trying to push a SwiftUI view from UIKit using UIHostingController. In the new view there is a button in the right side of the navigation bar, but it pops after the push animation. I can't make it appear with an animation like in a normal UIViewController. I tried adding the button in the navigationItem of the hosting controller and in the toolbar of the SwiftUI but none gives a smooth animation. I've made a small test and this are the results. This is the code: class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() title = "Home" } @IBAction func buttonNavPressed(_ sender: Any) { let vc = UIHostingController(rootView: ContentView()) vc.navigationItem.title = "NavItem Button" vc.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(sayHello)) navigationController?.pushViewController(vc, animated: true) } @IBAction func buttonSwiftUIPressed(_ sender: Any) { let vc = UIHostingController(rootView: ContentViewWithButton()) navigationController?.pushViewController(vc, animated: true) } @objc func sayHello() { print("Hello") } } struct ContentView: View { var body: some View { Text("No button") } } struct ContentViewWithButton: View { var body: some View { Text("With button") .navigationTitle("SwuitUI W Button") .toolbar { ToolbarItem(placement: .topBarTrailing) { Button(action: { print("Hello") }, label: { Image(systemName: "camera") } ) } } } } There is any workaround to this problem?
0
0
318
Dec ’24
NSToolbarItemGroup dynamically update subitems in toolbar
Developing on Monterey 12.7.5 I'm having trouble with updating subitems on NSToolbarItemGroup when selecting the item directly from the NSToolbar items array. I select the group item off the items array on the toolbar, and then call setSubitems: on the item, with a new array of NSToolbarItems. The group item disappears from the toolbar. It seems to leave a blank invisible item in the toolbar taking up space. I can't manually reinsert the item into the toolbar until I drag out the blank item, then drag back in the real item. Once dragged back in from the palette it displays correctly. The workaround I've come up with is to remove the item with NSToolbar removeItemAtIndex: and reinsert it with NSToollbar insertItemWithItemIdentifier:atIndex:. This works to update the subitems. Every other toolbar item property that I've tried has been able to update the item directly in the toolbar. It's only the group item's subitems that don't want to update correctly. Is there a correct way to do this that I'm missing? Calling [toolbar validateVisibleItems] didn't seem to help.
Topic: UI Frameworks SubTopic: AppKit Tags:
0
0
389
Nov ’24
Applying NSLayoutConstraints makes NSTableView unresponsive
In MacOS app I present modally NSTableView. The table is created in IB and its data and functionality are handled in corresponding NSViewController. As long as the positioning of modally presented table is left to the system, the tableview is placed in the center of the presenting view controller and everything works fine. But if I apply NSLayoutConstraints to position it as I need for visual design reasons, the table stops responding to mouse clicks. Here's the code inside the presenting view controller: bookmarks_TVC = Bookmarks_TVC() bookmarks_TVC.view.translatesAutoresizingMaskIntoConstraints = false self.present(bookmarks_TVC, animator: ModalPresentationAnimator()) NSLayoutConstraint.activate([ self.bookmarks_TVC.view.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant:410), self.bookmarks_TVC.view.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 170) ]) Once again, without NSLayoutConstraints the table responds as expected. Once the constraints are added, it becomes unresponsive. Thanks in advance for any helpful suggestions.
Topic: UI Frameworks SubTopic: AppKit
0
0
352
Dec ’24
LazyHstack in SwiftUI not supporting varying height views
In SwiftUI I want to create a list with LazyVstack and each row item in the LazyVstack is a LazyHstack of horizontally scrollable list of images with some description with line limit of 3 and width of every item is fixed to 100 but height of every item is variable as per description text content. But in any of the rows if the first item has image description of 1 line and the remaining items in the same row has image description of 3 lines then the LazyHStack is truncating all the image descriptions in the same row to one line making all the items in that row of same height. Why LazyHStack is not supporting items of varying height ? Expected behaviour should be that height of every LazyHStack should automatically adjust as per item content height. But it seems SwiftUI is not supporting LazyHstack with items of varying height. Will SwiftUI ever support this feature?
Topic: UI Frameworks SubTopic: SwiftUI
0
0
249
Feb ’25
Moving SceneDelegate to a different target
I have a SwiftUI project which has the following hierarchy: IOSSceneDelegate (App target) - depends on EntryPoint and Presentation static libs. Presentation (Static library) - Depends on EntryPoint static lib. Contains UI related logic and updates the UI after querying the data layer. EntryPoint (Static library) - Contains the entry point, AppDelegate (for its lifecycle aspects) etc. I've only listed the relevant targets here. SceneDelegate was initially present in EntryPoint library, because the AppDelegate references it when a scene is created. public func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -&gt; UISceneConfiguration { // Set the SceneDelegate dynamically let sceneConfig: UISceneConfiguration = UISceneConfiguration(name: "mainWindow", sessionRole: connectingSceneSession.role) sceneConfig.delegateClass = SceneDelegate.self return sceneConfig } The intent is to move the SceneDelegate to the Presentation library. When moved, the EntryPoint library fails to compile because it's referencing the SceneDelegate (as shown above). To remove this reference, I tried to set up the SceneDelegate in the old way - In the info.plist file, mention a SceneConfiguration and set the SceneDelegate in Presentation. // In the Info.plist file &lt;key&gt;UIApplicationSceneManifest&lt;/key&gt; &lt;dict&gt; &lt;key&gt;UIApplicationSupportsMultipleScenes&lt;/key&gt; &lt;true/&gt; &lt;key&gt;UISceneConfigurations&lt;/key&gt; &lt;dict&gt; &lt;key&gt;UIWindowSceneSessionRoleApplication&lt;/key&gt; &lt;array&gt; &lt;dict&gt; &lt;key&gt;UISceneConfigurationName&lt;/key&gt; &lt;string&gt;Default Configuration&lt;/string&gt; &lt;key&gt;UISceneDelegateClassName&lt;/key&gt; &lt;string&gt;Presentation.SceneDelegate&lt;/string&gt; &lt;/dict&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/dict&gt; // In the AppDelegate public func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -&gt; UISceneConfiguration { // Refer to a static UISceneconfiguration listed in the info.plist file return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } As shown above, the Presentation.SceneDelegate is referred in the Info.plist file and the reference is removed from the AppDelegate (in EntryPoint library). The app target compiles, but when I run it, the SceneDelegate is not invoked. None of the methods from the SceneDelegate (scene(_:willConnectTo:options:), sceneDidDisconnect(_:), sceneDidEnterBackground(_:) etc.) are invoked. I only get the AppDelegate logs. It seems like the Configuration is ignored because it was incorrect. Any thoughts? Is it possible to move the SceneDelegate in this situation?
0
1
373
Feb ’25
@State memory leak Xcode 16.2
Hi, A class initialized as the initial value of an @State property is not released until the whole View disappears. Every subsequent instance deinitializes properly. Am I missing something, or is this a known issue? struct ContentView: View { // 1 - init first SimpleClass instance @State var simpleClass: SimpleClass? = SimpleClass(name: "First") var body: some View { VStack { Text("Hello, world!") } .task { try? await Task.sleep(for: .seconds(2)) // 2 - init second SimpleClass instance and set as new @State // "First" should deinit simpleClass = SimpleClass(name: "Second") // 3 - "Second" deinit just fine simpleClass = nil } } } class SimpleClass { let name: String init(name: String) { print("init: \(name)") self.name = name } deinit { print("deinit: \(name)") } } output: init: First init: Second deinit: Second Thanks
0
0
255
Feb ’25
SwiftUI Audio File Export via draggable
Hey everyone, TL;DR How do I enable a draggable TableView to drop Audio Files into Apple Music / Rekordbox / Finder? Intro / skip me I've been dabbling into Swift / SwiftUI for a few weeks now, after roughly a decade of web development. So far I've been able to piece together many things, but this time I'm stuck for hours with no success using Forums / ChatGPT / Perplexity / Trial and Error. The struggle Sometimes the target doesn't accept the dropping at all sometimes the file data is failed to be read when the drop succeeds, then only as a stream in apple music My lack of understanding / where exactly I'm stuck I think the right way is to use UTType.fileUrl but this is not accepted by other applications. I don't understand low-level aspects well enough to do things right. The code I'm just going to dump everything here, it includes failed / commented out attempts and might give you an Idea of what I'm trying to achieve. // // Tracks.swift // Tuna Family // // Created by Jan Wirth on 12/12/24. // import SwiftySandboxFileAccess import Files import SwiftUI import TunaApi struct LegacyTracks: View { @State var tracks: TunaApi.LoadTracksQuery.Data? func fetchData() { print("fetching data") Network.shared.apollo.fetch(query: TunaApi.LoadTracksQuery()) { result in switch result { case .success(let graphQLResult): self.tracks = graphQLResult.data case .failure(let error): print("Failure! Error: \(error)") } } } @State private var selection = Set<String>() var body: some View { Text("Tracks").onAppear{ fetchData() } if let tracks = tracks?.track { Table(of: LoadTracksQuery.Data.Track.self, selection: $selection) { TableColumn("Title", value: \.title) } rows : { ForEach(tracks) { track in TableRow(track) .draggable(track) // .draggable((try? File(path: track.dropped_source?.path ?? "").url) ?? test_audio.url) // This causes a compile-time error // .draggable(test_audio.url) // .draggable(DraggableTrack(url: test_audio.url)) // .itemProvider { // let provider = NSItemProvider() // if let path = self.dropped_source?.path { // if let f = try? File(path: path) { // print("Transferring", f.url) // // // } // } // // provider.register(track) // return provider // } // This does not } } .contextMenu(forSelectionType: String.self) { items in // ... Button("yoooo") {} } primaryAction: { items in print(items) // This is executed when the row is double clicked } } else { Text("Loading") } // } } } //extension Files.File: Transferable { // public static var transferRepresentation: some TransferRepresentation { // FileRepresentation(exportedContentType: .audio) { url in // SentTransferredFile( self.) // } // } //} struct DraggableTrack: Transferable { var url: URL public static var transferRepresentation: some TransferRepresentation { FileRepresentation (exportedContentType: .fileURL) { item in SentTransferredFile(test_audio.url, allowAccessingOriginalFile: true) } // FileRepresentation(contentType: .init(filenameExtension: "m4a")) { // print("file", $0) // print("Transferring fallback", test_audio.url) // return SentTransferredFile(test_audio.url, allowAccessingOriginalFile: true) // } // importing: { received in // // let copy = try Self.(source: received.file) // return Self.init(url: received.file) // } // ProxyRepresentation(exporting: \.url.absoluteString) } } extension LoadTracksQuery.Data.Track: @retroactive Identifiable { } import UniformTypeIdentifiers extension LoadTracksQuery.Data.Track: @retroactive Transferable { // static func getKind() -> UTType { // var kind: UTType = UTType.item // if let path = self.dropped_source?.path { // if let f = try? File(path: path) { // print("Transferring", f.url) // if (f.extension == "m4a") { // kind = UTType.mpeg4Audio // } // if (f.extension == "mp3") { // kind = UTType.mp3 // } // if (f.extension == "flac") { // kind = UTType.flac // } // if (f.extension == "wav") { // kind = UTType.wav // } // // } // } // return kind // } public static var transferRepresentation: some TransferRepresentation { ProxyRepresentation { $0.dropped_source?.path ?? "" } FileRepresentation(exportedContentType: .fileURL) { <#Transferable#> in SentTransferredFile(<#T##file: URL##URL#>, allowAccessingOriginalFile: <#T##Bool#>) } // FileRepresentation(contentType: .fileURL) { // print("file", $0) // if let path = $0.dropped_source?.path { // if let f = try? File(path: path) { // print("Transferring", f.url) // return SentTransferredFile(f.url, allowAccessingOriginalFile: true) // } // } // print("Transferring fallback", test_audio.url) // return SentTransferredFile(test_audio.url, allowAccessingOriginalFile: true) // } // importing: { received in // // let copy = try Self.(source: received.file) // return Self.init(_fieldData: received.file) // } // ProxyRepresentation(exporting: \.title) } }
0
0
427
Dec ’24
Siri Intent Dialog with custom SwiftUIView not responding to buttons with intent
I have created an AppIntent and added it to shortcuts to be able to read by Siri. When I say the phrase, the Siri intent dialog appears just fine. I have added a custom SwiftUI View inside Siri dialog box with 2 buttons with intents. The callback or handling of those buttons is not working when initiated via Siri. It works fine when I initiate it in shortcuts. I tried using the UIButton without the intent action as well but it did not work. Here is the code. static let title: LocalizedStringResource = "My Custom Intent" static var openAppWhenRun: Bool = false @MainActor func perform() async throws -> some ShowsSnippetView & ProvidesDialog { return .result(dialog: "Here are the details of your order"), content: { OrderDetailsView() } } struct OrderDetailsView { var body: some View { HStack { if #available(iOS 17.0, *) { Button(intent: ModifyOrderIntent(), label : { Text("Modify Order") }) Button(intent: CancelOrderIntent(), label : { Text("Cancel Order") }) } } } } struct ModifyOrderIntent: AppIntent { static let title: LocalizedStringResource = "Modify Order" static var openAppWhenRun: Bool = true @MainActor func perform() async throws -> some OpensIntent { // performs the deeplinking to app to a certain page to modify the order } } struct CancelOrderIntent: AppIntent { static let title: LocalizedStringResource = "Cancel Order" static var openAppWhenRun: Bool = true @MainActor func perform() async throws -> some OpensIntent { // performs the deeplinking to app to a certain page to cancel the order } } Button(action: { if let url = URL(string: "myap://open-order") { UIApplication.shared.open(url) } }
0
0
316
Mar ’25
macos 15, savepanel return the wrong path when saving files occasionally
macOS: 15.0 macFUSE: 4.8.3 I am using rclone + macFUSE and mount my netdisk where it has created three subdirectories in its root directory: /user, /share, and /group. When I save a file to /[root]/user using NSSavePanel and name it test.txt, I expect the file to be saved as: /[root]/user/test.txt However, occasionally, the delegate method: - (BOOL)panel:(id)sender validateURL:(NSURL *)url error:(NSError **)outError { } returns an incorrect path: /[root]/test.txt This issue only occurs when selecting /user. The same operation works correctly for /share and /group. Is there any logs I could provide to help solving this issue? Many thanks!
Topic: UI Frameworks SubTopic: AppKit Tags:
0
0
348
Feb ’25
Detect change to apps Screen Time Access
I'm creating an app which gamifies Screen Time reduction. I'm running into an issue with apples Screen Time setting where the user can disable my apps "Screen Time access" and get around losing the game. Is there a way to detect when this setting is disabled for my app? I've tried using AuthorizationCenter.shared.authorizationStatus but this didn't do the trick. Does anyone have an ideas?
0
0
383
Feb ’25
swift DeviceActivityReport run in background
DeviceActivityReport presents statistics for a device: https://developer.apple.com/documentation/deviceactivity/deviceactivityreport The problem: DeviceActivityReport can present statistics with a delay for a parent device (when DeviceActivityReport is presenting, the DeviceActivityReportExtension is called to process the statistics). One possible solution is to call DeviceActivityReport periodically throughout the day in a child device. However, the app will not be available all day. Is there any way to run DeviceActivityReport in the background? I have tried the following approach, but it didn’t work (DeviceActivityReportExtension didnt call): let hostingController: UIHostingController? = .init(rootView: DeviceActivityReport(context, filter: filter)) hostingController?.view.frame = .init(origin: .zero, size: .init(width: 100, height: 100)) hostingController?.beginAppearanceTransition(true, animated: false) hostingController?.loadView() hostingController?.viewDidLoad() try? await Task.sleep(for: .seconds(0.5)) hostingController?.viewWillAppear(true) hostingController?.viewWillLayoutSubviews() try? await Task.sleep(for: .seconds(0.5)) hostingController?.viewDidAppear(true) try? await Task.sleep(for: .seconds(0.5)) hostingController?.didMove(toParent: rootVC) try? await Task.sleep(for: .seconds(0.5)) hostingController?.viewWillLayoutSubviews() hostingController?.viewDidLayoutSubviews() hostingController?.view.layoutIfNeeded() hostingController?.view.layoutSubviews() hostingController?.endAppearanceTransition() Is there any way to run DeviceActivityReport in the background? (when app is not visible/closed). The main problem is call DeviceActivityReport
0
0
551
Nov ’24