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.

Post

Replies

Boosts

Views

Activity

How to make third party peripheral discoverable using iOS 18 AccessorySetupKit
As the new feature is launched I also want to make user experience smoother in my app using the AccessorySetupKit. But my peripheral is not discoverable. But another ios device with same advertisement data is discoverable by AccessorySetupKit. I didn't find much information on the documents related to the third party connection. I'm not sure if the third party peripheral should be MFI supported or anything else is required. Is there anything I'm missing here to fullfill the requirement, please let me know. Below is the code i"m using to discover the peripheral. Once again iOS to iOS discovery is working, facing issue with third party peripheral is not discovering. private var session = ASAccessorySession() var pickerDismissed = true private static let perepheral: ASPickerDisplayItem = { let descriptor = ASDiscoveryDescriptor() descriptor.bluetoothServiceUUID = PublisherClass.serviceUUID return ASPickerDisplayItem( name: "Test_Name", productImage: UIImage(named: "sample")!, descriptor: descriptor ) }() override func viewDidLoad() { super.viewDidLoad() self.session.activate(on: DispatchQueue.main, eventHandler: handleSessionEvent(event:)) } @IBAction func presentPicker() { session.showPicker(for: [Self.perepheral]) { error in if let error { print("Failed to show picker due to: \(error.localizedDescription)") } } } private func handleSessionEvent(event: ASAccessoryEvent) { switch event.eventType { case .accessoryAdded, .accessoryChanged: guard let accessory = event.accessory else { return } print("\(accessory)") case .activated: guard let accessory = session.accessories.first else { return } print("\(accessory)") case .accessoryRemoved: print("Received event type accessoryRemoved)") case .pickerDidPresent: pickerDismissed = false case .pickerDidDismiss: pickerDismissed = true default: print("Received event type \(event.eventType)") } } } I also added these details in plist NSAccessorySetupKitSupports Bluetooth NSAccessorySetupBluetoothServices
0
0
194
Aug ’24
ControlWigdet Open APP with URL
This code can open app, but the deep link is not send to the app. It doesn't seem to call the UIApplicationDelegate's "application(_:open:options:)" method, so I can't read the link string that was passed in func perform() async throws -> some IntentResult & OpensIntent { guard let url = URL(string: "myapp://myappintent") else { // throw an error of your choice here } return .result(opensIntent: OpenURLIntent(deepLink)) }
1
1
320
Aug ’24
Calling viewDidAppear intentionally
I am developing SDK and swizzling viewDidAppear. I have a customer who implements a custom TabBar Navigation where VC's are added to the hierarchy on the first load, and then, he changes the opacity to the currently displayed tab so the next time the user sees the tab - viewDidAppear isn't called, so my code isn't called. I'm attaching a sample project which reproduces that. Is there any way to trigger ViewDidAppear intentionally? If yes, what can be the side effect of doing that? Do I have any other alternative in this case? @main struct DemoCustomTabViewApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { TabBarRouterView() } } } import UIKit // MARK: - TabBarItem (unchanged) enum TabBarItem: Identifiable, CaseIterable { case home, search, profile var id: Self { self } var title: String { switch self { case .home: return "Home" case .search: return "Search" case .profile: return "Profile" } } var icon: String { switch self { case .home: return "house" case .search: return "magnifyingglass" case .profile: return "person" } } } // MARK: - NavigationControllerView struct NavigationControllerView: UIViewControllerRepresentable { var rootViewController: UIViewController func makeUIViewController(context: Context) -> UINavigationController { let navigationController = UINavigationController(rootViewController: rootViewController) return navigationController } func updateUIViewController(_ uiViewController: UINavigationController, context: Context) {} } // MARK: - TabBarRouterViewModel class TabBarRouterViewModel: ObservableObject { @Published var currentTab: TabBarItem = .home @Published var cachedViews: [TabBarItem: AnyView] = [:] let tabs: [TabBarItem] = TabBarItem.allCases func switchTab(to tab: TabBarItem) { currentTab = tab } func createView(for tab: TabBarItem) -> AnyView { if let cachedView = cachedViews[tab] { return cachedView } let rootViewController: UIViewController switch tab { case .home: rootViewController = UIHostingController(rootView: Text("Home View")) case .search: rootViewController = UIHostingController(rootView: Text("Search View")) case .profile: rootViewController = UIHostingController(rootView: Text("Profile View")) } let navigationView = NavigationControllerView(rootViewController: rootViewController) let anyView = AnyView(navigationView) cachedViews[tab] = anyView return anyView } } // MARK: - CustomTabBarView (unchanged) struct CustomTabBarView: View { let tabs: [TabBarItem] @Binding var selectedTab: TabBarItem let onTap: (TabBarItem) -> Void var body: some View { HStack { ForEach(tabs) { tab in Spacer() VStack { Image(systemName: tab.icon) .font(.system(size: 24)) Text(tab.title) .font(.caption) } .foregroundColor(selectedTab == tab ? .blue : .gray) .onTapGesture { onTap(tab) } Spacer() } } .frame(height: 60) .background(Color.white) .shadow(radius: 2) } } // MARK: - TabBarRouterView struct TabBarRouterView: View { @StateObject private var viewModel = TabBarRouterViewModel() var body: some View { VStack(spacing: .zero) { contentView CustomTabBarView( tabs: viewModel.tabs, selectedTab: $viewModel.currentTab, onTap: viewModel.switchTab ) } .edgesIgnoringSafeArea(.bottom) } private var contentView: some View { ZStack { ForEach(viewModel.tabs) { tab in viewModel.createView(for: tab) .opacity(viewModel.currentTab == tab ? 1.0 : 0.0) } } } }
1
0
251
Aug ’24
Fatal Exception: NSInternalInconsistencyException UIGraphicsBeginImageContext() failed to allocate CGBitampContext: size={0, 1133}, scale=2.000000, bitmapInfo=0x2002. Use UIGraphicsImageRenderer to avoid this assert.
I have a .Net MAUI App. As soon as i close the app or put in the background the app crashes instantly. It only happens on OS version: iPad OS 17.5.1 Model:iPad mini (6th generation). Below is the exception logged on firebase crashlytics Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UIGraphicsBeginImageContext() failed to allocate CGBitampContext: size={0, 0}, scale=3.000000, bitmapInfo=0x2002. Use UIGraphicsImageRenderer to avoid this assert.' Any suggestions or ideas ?
0
0
207
Aug ’24
App Icon all black on ios17, works on iOS18, building app in Xcode16 beta
In my app I added an AppIcon in the Assets.xcassets folder. I added a any/dark/tinted version of the app icon, in 1024x1024 resolution as a HEIC file, specifying a "single size" iOS option. When I build and run the app in xcode16 beta on iOS18 the icon works as expected, but when I run the same app on iOS17 the icon just shows up as a black rectangle. How do I get the app icon to work correctly on both iOS18 and iOS17?
1
0
310
Aug ’24
On Continue User Activity with Swift UI
Hi All, I'm very new to iOS development and Swift UI is my first coding language. I'm trying to link the users search results in Spotlight with the detail view that is stored in Core Data. I can search for users data in spotlight but when I tap on it, it's only appearing in the main view of the app. Is there anyways that I can use .onContinueUserActivity at the launch of the app or is there any different code that I have to use? I've searched for many articles but I couldn't get a solution. It would be good if anyone can share some links or guide here. Thank you. .onContinueUserActivity(DetailView.productUserActivityType) { userActivity in             if let product = try? userActivity.typedPayload(Product.self) {                 selectedProduct = product.id.uuidString             }         } I get this code from Apple's State restoration app but I can't use this with Core Data.
1
0
1.2k
Aug ’21
tvOS 18.0 Siri back button behavior bug
On testing my app with tvOS 18, I have noticed the Siri Remote back button no longer provides system-provided behavior when interacting with tab bar controller pages. Instead of moving focus back to the tab bar when pressed, the back button will close the app, as if the Home button was pressed. This occurs both on device and in the Simulator. Create tvOS project with a tab bar controller. Create pages/tabs which contain focusable items (ie. buttons) Scroll down to any focusable item (ie. a button or UICollectionView cell) Hit the Siri Remote back button. See expect behavior below: Expected behavior: System-provided behavior should move focus back to the tab bar at the top of the screen. Actual results: App is closed and user is taken back to the Home Screen. Has anyone else noticed this behavior?
1
0
338
Aug ’24
Tab bar for tvOS 18 is positioned too low (bug?)
I've noticed the tab bar in tvOS 18 (beta) is positioned lower on the TV screen than in previous versions. Bug? I see no documentation on this important UI change... If this is not a bug, is there any way to adjust the y coordinate of the tab bar location in tvOS 18? I would really like to restore this to the previous location for my app and avoid having to do OS-conditional constraints for all my views/pages.
2
0
257
Aug ’24
Navigation Bar Buttons Abbreviated with Ellipses Despite No Accessibility Settings
Hi everyone, We have a user experiencing a display issue. Here's a screenshot they shared with us. Unlike in the simulator, where we see three icons, their display shows two buttons abbreviated with ellipses. The device is iPhone 12 mini with iOS 17.6.1. The user isn't using any accessibility settings or large text size. Does anyone know what setting might be causing this? Any advice would be appreciated! Thanks!
1
0
257
Aug ’24
Screen Corner Radius Border
I'd like an effect similar to the iOS 18 Siri, with a border/stroke extending around the view including the corner radius of the screen. This is challenging as "logically" the view is rectangular and those radii don't really exist. I've seen some posts around the web about _displayCornerRadius which appears to be what would work but it is private and as far as I can tell never mentioned anywhere else. Does anyone know of a way to achieve a border around a view that correctly wraps around the corners of the rounded screen? Currently using SwiftUI but open to any solutions.
3
0
299
Aug ’24
WidgetKit complications do not appear on watchOS 11 beta 5
Third-party WidgetKit complications on watchOS 11 beta 5 are not appearing in the list of available complications. They have also disappeared from watch faces where they were installed. The exact same complications were working fine on earlier betas. This is happening on device, but not in simulator. This issue may be related to FB14684253, which was fixed with the release of Xcode beta 5. However, Xcode beta 5 does not fix the issue on Apple Watch. As a sanity check, I also tried with the Backyard Birds sample project, and the complications for that app aren't appearing on device either. Filed as FB14689021.
3
2
393
Aug ’24
Show my app first in the list of apps in the UIActivityViewController share dialog for a custom file extension exported by my app
My app exports a custom file type identifier for a file that it exports to share between other users of the same app. However in the list of apps in UIActivityViewController view, my app is listed far off screen. How can I make my app which owns the file type appear first in the list, instead of seeing many irrelevant apps that can't actually open my file? Plist snippets: <key>CFBundleDocumentTypes</key> <array> <dict> <key>CFBundleTypeName</key> <string>My Custom App File</string> <key>LSHandlerRank</key> <string>Owner</string> <key>LSItemContentTypes</key> <array> <string>abc.myapp.myextension</string> </array> </dict> </array> <key>UTExportedTypeDeclarations</key> <array> <dict> <key>UTTypeConformsTo</key> <array> <string>public.content</string> <string>public.data</string> </array> <key>UTTypeDescription</key> <string>My Custom App File</string> <key>UTTypeIconFiles</key> <array/> <key>UTTypeIdentifier</key> <string>abc.myapp.myextension</string> <key>UTTypeTagSpecification</key> <dict> <key>public.filename-extension</key> <array> <string>myextension</string> </array> <key>public.mime-type</key> <array> <string>application/octet-stream</string> </array> </dict> </dict> </array>
0
0
216
Aug ’24
How can we performantly scroll to a target location using TextKit 2?
How can we performantly scroll to a target location using TextKit 2? Hi everyone, I'm building a custom text editor using TextKit 2 and would like to scroll to a target location efficiently. For instance, I would like to move to the end of a document seamlessly, similar to how users can do in standard text editors by using CMD + Down. Background: NSTextView and TextEdit on macOS can navigate to the end of large documents in milliseconds. However, after reading the documentation and experimenting with various ideas using TextKit 2's APIs, it's not clear how third-party developers are supposed to achieve this. My Code: Here's the code I use to move the selection to the end of the document and scroll the viewport to reveal the selection. override func moveToEndOfDocument(_ sender: Any?) { textLayoutManager.ensureLayout(for: textLayoutManager.documentRange) let targetLocation = textLayoutManager.documentRange.endLocation let beforeTargetLocation = textLayoutManager.location(targetLocation, offsetBy: -1)! textLayoutManager.textViewportLayoutController.layoutViewport() guard let textLayoutFragment = textLayoutManager.textLayoutFragment(for: beforeTargetLocation) else { return } guard let textLineFragment = textLayoutFragment.textLineFragment(for: targetLocation, isUpstreamAffinity: true) else { return } let lineFrame = textLayoutFragment.layoutFragmentFrame let lineFragmentFrame = textLineFragment.typographicBounds.offsetBy(dx: 0, dy: lineFrame.minY) scrollToVisible(lineFragmentFrame) } While this code works as intended, it is very inefficient because ensureLayout(_:) is incredibly expensive and can take seconds for large documents. Issues Encountered: In my attempts, I have come across the following two issues. Estimated Frames: The frames of NSTextLayoutFragment and NSTextLineFragment are approximate and not precise enough for scrolling unless the text layout fragment has been fully laid out. Laying out all text is expensive: The frames become accurate once NSTextLayoutManager's ensureLayout(for:) method has been called with a range covering the entire document. However, ensureLayout(for:) is resource-intensive and can take seconds for large documents. NSTextView, on the other hand, accomplishes the same scrolling to the end of a document in milliseconds. I've tried using NSTextViewportLayoutController's relocateViewport(to:) without success. It's unclear to me whether this function is intended for a use case like mine. If it is, I would appreciate some guidance on its proper usage. Configuration: I'm testing on macOS Sonoma 14.5 (23F79), Swift (AppKit), Xcode 15.4 (15F31d). I'm working on a multi-platform project written in AppKit and UIKit, so I'm looking for either a single solution that works in both AppKit and UIKit or two solutions, one for each UI framework. Question: How can third-party developers scroll to a target location, specifically the end of a document, performantly using TextKit 2? Steps to Reproduce: The issue can be reproduced using the example project (download from link below) by following these steps: Open the example project. Run the example app on a Mac. The example app shows an uneditable text view in a scroll view. The text view displays a long text. Press the "Move to End of Document" toolbar item. Notice that the text view has scrolled to the bottom, but this took several seconds (~3 seconds on my MacBook Pro 16-inch, 2021). The duration will be shown in Xcode's log. You can open the ExampleTextView.swift file and find the implementation of moveToEndOfDocument(_:). Comment out line 84 where the ensureLayout(_:) is called, rerun the app, and then select "Move to End of Document" again. This time, you will notice that the text view moves fast but does not end up at the bottom of the document. You may also open the large-file.json in the project, the same file that the example app displays, in TextEdit, and press CMD+Down to move to the end of the document. Notice that TextEdit does this in mere milliseconds. Example Project: The example project is located on GitHub: https://github.com/simonbs/apple-developer-forums/tree/main/how-can-we-performantly-scroll-to-a-target-location-using-textkit-2 Any advice or guidance on how to achieve this with TextKit 2 would be greatly appreciated. Thanks in advance! Best regards, Simon
10
9
1.2k
Aug ’24
Core data turning objects into faults inappropriately
It seems that when an entity has and ordered to-many relationship to the same entity, inserting an object into the ordered set causes other objects of the set to turn into faults during the next save of the managed object context. I verified it with several applications. For the sake of example, the entity will be called Folder and the ordered to-many relationship subfolders (an NSOrdereset), with a cascade delete rule. The reciprocal to-one relationship is called parent. Assuming you have a Folder object with two subfolders, removing the last subfolder from the set (setting its parent to nil) and reinserting it at index 0 with insertObject:<>inSubfoldersAtIndex:0 will turn the other subfolder into a fault at the next save. Now assuming that other folder has a name attribute (NSString) that is bound to a textfield in your UI, the name of that subfolder will disappear when the context saves, since it becomes nil while the subfolder is turned into a fault. Is this expected behavior? Note: I'm using Objective C, Xcode 15 and macOS sonoma, but I've seen this issue occur on previous macOS versions.
4
0
270
Aug ’24
SwiftData fatal error "Never access a full future backing data"
My app started crashing a ton with Xcode 16 beta 1 / iOS 18 because of "Thread 1: Fatal error: Never access a full future backing data". I was hoping this would be resolved with beta 2, but unfortunately this is not the case. I'm having a tough time reproducing this bug in a small sample project – I'd appreciate any hints as to what might be causing this. Full error: Thread 1: Fatal error: Never access a full future backing data - PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://10A5A93C-DC7F-40F3-92DB-F4125E1C7A73/MyType/p2), implementation: SwiftData.PersistentIdentifierImplementation) with Optional(3BF44A2D-256B-4C40-AF40-9B7518FD9FE6)
7
7
854
Jun ’24
Widget cannot retrieve Core Data on a real device.
My app uses Core Data and has enabled App Groups for data sharing between the App and Widget. In my app, there's a Core Data entity called Task. As per the documentation's suggestion, I've separately implemented a TaskData struct that conforms to AppEntity. I've also implemented TaskDataQuery: EntityQuery, which includes a method called suggestedEntities. This method fetches all Tasks from the main context and uses Task.toTaskData. Following the documentation, I've implemented the corresponding WidgetConfigurationIntent, which holds: @Parameter(title: "Task") var task: TaskData as well as the corresponding AppIntentTimelineProvider to implement the provider. I haven't encountered any retrieval issues on the simulator; everything works perfectly. However, the problem arises when I deploy to a physical device. Users report that their widgets can't retrieve any data. Specifically, when users long-press the widget to set up a task, it remains in a Loading state, unable to fetch any Core Data. I've looked through some resources, and it seems this might be a common issue with iOS 17? How can I resolve this issue? Has anyone encountered this or can offer any suggestions? This has been troubling me for several days now, and it's causing my product to continually lose users. I'm really upset about it. Any advice is welcome.
1
0
156
Aug ’24
iOS18 Live Activity failed to show sometimes
In a music streaming app, when using Activity.request to activate the Dynamic Island, the system’s Now Playing interface appears correctly. However, the app's live activities, lock screen, and other related features fail to display properly. During debugging, the following code is used: activity = try Activity.request(attributes: attributes, contentState: contentState, pushType: .token) if !NMABTestManager.default().is(inTest: "FH-NewLiveActivityPush") { // Listen to push token updates if activity != nil { tokenUpdatesTask?.cancel() tokenUpdatesTask = Task.detached { for await tokenData in self.activity!.pushTokenUpdates { let mytoken = tokenData.map { String(format: "%02x", $0) }.joined().uppercased() // pushToken is Data, needs to be converted to String using the above method before being passed to the server self.pushToken = mytoken } } } } } catch (let error) { print("Error Starting Live Activity: \(error.localizedDescription)") } In this scenario, the push token is returned correctly, and no errors are triggered. This issue did not occur in iOS 17 but appears sporadically in iOS 18. Once it occurs, it cannot be resolved through restarting or other means. feedbackid:FB14763873, i upload my sysdisagnose
2
0
417
Aug ’24