I’m having a weird UIKit problem. I have a bunch of views in a UIScrollView and I add a UIContextMenuInteraction to all of them when the view is first loaded. Because they're in a scroll view, only some of the views are initially visible.
The interaction works great for any of the views that are initially on-screen, but if I scroll to reveal new subviews, the context menu interaction has no effect for those.
I used Xcode's View Debugger to confirm that my interaction is still saved in the view's interactions property, even for views that were initially off-screen and were then scrolled in.
What could be happening here?
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.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
App update in which there were no changes regarding the widget. Just after it updated, the widget turns black in some cases. It also appears black in the widget gallery. Removing and adding it again did not work in this case, only after an iOS restart it works fine again
This is the log
2025-03-20 02:14:05.961611 +0800 Content load failed: unable to find or unarchive file for key: [com.aa.bb::com.aa.bb.widget:cc_widget:systemMedium::360.00/169.00/23.00:(null)~(null)] on no host. The session may still produce one shortly. Error: Using url file:///private/var/mobile/Containers/Data/PluginKitPlugin/51C5E4F2-6F1F-4466-A428-73C73B9CC887/SystemData/com.apple.chrono/placeholders/cc_widget/systemMedium----360.00w--169.00h--23.00r--1f--0.00t-0.00l-0.00b0.00t.chrono-timeline ... Error Domain=NSCocoaErrorDomain Code=4 "file“systemMedium----360.00w--169.00h--23.00r--1f--0.00t-0.00l-0.00b0.00t.chrono-timeline”not exist。" UserInfo={NSFilePath=/private/var/mobile/Containers/Data/PluginKitPlugin/51C5E4F2-6F1F-4466-A428-73C73B9CC887/SystemData/com.apple.chrono/placeholders/cc_widget/systemMedium----360.00w--169.00h--23.00r--1f--0.00t-0.00l-0.00b0.00t.chrono-timeline, NSUnderlyingError=0xa693d3a80 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
Hello.
I use NavigationStack for navigating in app. I have 4 screens - A, B, C, D. In some moment I have path [A, B, C] for NavigationStack. After user did action I should show path [A, B, D]. In other hands I should replace screen C with screen D.
struct HomeView: View {
@ObservedObject var viewModel: HomeViewModel
var body: some View {
NavigationStack(path: $viewModel.path) {
ContentView()
.navigationDestination(for: HomeViewModel.Path.self) { destination in
// B, C, D views here...
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
Solution looks like same as for UIKit. I replaced last item in stack. It works, but "push" animation broke.
var updatedPath = self.path
updatedPath.removeLast()
updatedPath.append(newPathItem)
self.path = updatedPath
I found suggest in Internet that you can remove view from stack after some delay. But it has some magic. For example 1 second delay works properly on iOS 18, but cause crash on iOS 16. 1 millisecond delay works on iOS 16, but sometimes didn't.
self.path.append(newPathItem)
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(1000)) {
UIView.setAnimationsEnabled(false)
self.path.remove(at: self.path.count - 2)
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(1)) {
UIView.setAnimationsEnabled(true)
}
}
It is easy task to replace current top screen in UINavigationController of UIKit. How I can do it properly in SwiftUI and save animation?
Hi,
I have an existing Mac app on the App Store with a couple of widgets as part of the app. I want to now add a new widget to the WidgetBundle. When I build the updated app with Xcode, and then run the updated app, the widgets list doesn't seem to get updated in Notification Center or in the WidgetKit Simulator.
I do have the App Store version installed in the /Applications folder as well, so there might be some conflict. What's the trick to getting the widgets list to run the debug version?
Hi everyone,
frome time to time I see crash which Im not able to debug, because there is no line of my code where crash occured.
This is a crash log what Im getting from time to time of some users. In my device I never get this kind of crash.
0 libswiftCore.dylib 0x1172c _assertionFailure(_:_:flags:) + 208
1 libswiftCore.dylib 0x198624 KEY_TYPE_OF_DICTIONARY_VIOLATES_HASHABLE_REQUIREMENTS(_:) + 2980
2 libswiftCore.dylib 0xdb6c8 specialized _NativeDictionary.uncheckedRemove(at:isUnique:) + 534
3 libswiftCore.dylib 0xb250c Dictionary._Variant.setValue(_:forKey:) + 204
4 libswiftCore.dylib 0x5a620 Dictionary.subscript.setter + 520
5 SwiftUICore 0xf62ec ForEachState.item(at:offset:) + 4340
6 SwiftUICore 0xf5054 ForEachState.forEachItem(from:style:do:) + 1796
7 SwiftUICore 0x2272f8 ForEachState.traitKeys.getter + 84
8 SwiftUICore 0x227298 ForEachList.traitKeys.getter + 24
9 SwiftUICore 0x227008 protocol witness for ViewList.traitKeys.getter in conformance SubgraphList + 76
10 SwiftUICore 0x227008 protocol witness for ViewList.traitKeys.getter in conformance SubgraphList + 76
11 SwiftUICore 0x227008 protocol witness for ViewList.traitKeys.getter in conformance SubgraphList + 76
12 SwiftUICore 0x227008 protocol witness for ViewList.traitKeys.getter in conformance SubgraphList + 76
13 SwiftUICore 0x2271fc DynamicViewList.WrappedList.traitKeys.getter + 88
27 SwiftUICore 0x226d18 specialized static SectionAccumulator.processUnsectionedContent(list:contentSubgraph:) + 84
28 SwiftUI 0x26afe0 ListSectionInfo.init(list:listAttribute:contentSubgraph:) + 132
29 SwiftUI 0x269bb0 UpdateCollectionViewListCoordinator.updateValue() + 1528
30 SwiftUI 0x785d4 partial apply for implicit closure #1 in closure #1 in closure #1 in Attribute.init<A>(_:) + 32
31 AttributeGraph 0xccac AG::Graph::UpdateStack::update() + 540
32 AttributeGraph 0xc870 AG::Graph::update_attribute(AG::data::ptr<AG::Node>, unsigned int) + 424
33 AttributeGraph 0xc444 AG::Subgraph::update(unsigned int) + 848
34 SwiftUICore 0x805a8 GraphHost.flushTransactions() + 860
35 SwiftUI 0x1ac84 closure #1 in _UIHostingView._renderForTest(interval:) + 24
36 SwiftUICore 0x7ffa8 partial apply for closure #1 in ViewGraphDelegate.updateGraph<A>(body:) + 28
37 SwiftUICore 0x7fd6c ViewRendererHost.updateViewGraph<A>(body:) + 120
38 SwiftUICore 0x7fce8 ViewGraphDelegate.updateGraph<A>(body:) + 84
39 SwiftUI 0x3e688 closure #1 in closure #1 in closure #1 in _UIHostingView.beginTransaction() + 172
40 SwiftUI 0x3e5d4 partial apply for closure #1 in closure #1 in closure #1 in _UIHostingView.beginTransaction() + 24
41 SwiftUICore 0x79720 closure #1 in static Update.ensure<A>(_:) + 56
42 SwiftUICore 0x796a4 static Update.ensure<A>(_:) + 100
43 SwiftUI 0x9c808 partial apply for closure #1 in closure #1 in _UIHostingView.beginTransaction() + 80
44 SwiftUICore 0x7f5e0 thunk for @callee_guaranteed () -> () + 28
45 SwiftUICore 0x6161c specialized closure #1 in static NSRunLoop.addObserver(_:) + 144
46 CoreFoundation 0x218a4 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 36
47 CoreFoundation 0x213f8 __CFRunLoopDoObservers + 552
48 CoreFoundation 0x75da8 __CFRunLoopRun + 948
49 CoreFoundation 0xc8284 CFRunLoopRunSpecific + 588
50 GraphicsServices 0x14c0 GSEventRunModal + 164
51 UIKitCore 0x3ee674 -[UIApplication _run] + 816
52 UIKitCore 0x14e88 UIApplicationMain + 340
53 SwiftUI 0x291ef8 closure #1 in KitRendererCommon(_:) + 168
54 SwiftUI 0x291e28 runApp<A>(_:) + 100
55 SwiftUI 0x291d0c static App.main() + 180
56 DholRainbow 0x3019e8 main + 4339145192 (DholRainbowApp.swift:4339145192)
57 ??? 0x1b0bf5de8 (Missing)
From Crashlytics I know at least human readable format of this error
Fatal error: Duplicate keys of type 'Contact' were found in a Dictionary. This usually means either that the type violates Hashable's requirements, or that members of such a dictionary were mutated after insertion.
I 've checked all my parts of code where Im using dictionary. This is a function which creating that particulary dictionary.
private func logsByDate() {
let groupedByDate = Dictionary(grouping: logs.filter { ($0.remoteParty as? Contact != nil) } ) {
$0.date.removeTimeStamp ?? .distantPast }.mapValues {
$0.compactMap { $0 }
}
var dayLogs = [DayLog]()
for date in groupedByDate {
var contacts = [CallLogContact]()
for log in logs.filter({ $0.date.removeTimeStamp ?? .distantPast == date.key }) {
if let contact = log.remoteParty as? Contact {
if contacts.firstIndex(where: {$0.contact == contact }) == nil {
let contactDayLogs = logs.filter({ $0.remoteParty as? Contact == contact && $0.date.removeTimeStamp == date.key})
contacts.append(
CallLogContact(
contact: contact,
logs: contactDayLogs,
lastCallLogDate: contactDayLogs.sorted(by: {$0.date > $1.date}).first?.date ?? .distantPast
)
)
}
}
}
dayLogs.append(DayLog(date: date.key, contact: contacts))
}
DispatchQueue.main.async {
self.groupedCallLogs = dayLogs
}
}
This function is called from 3 others functions based on notification from the server in case of new call log, fetched call logs and removed call logs.
I have a UITextField in my application, and I want to detect all the keys uniquely to perform all relevant task. However, there is some problem in cleanly identifying some of the keys.
I m not able to identify the backspace key press in the textField(_:shouldChangeCharactersIn:replacementString:) method.
Also I don't know how to detect the Caps Lock key.
I am intending to so this because I want to perform some custom handling for some keys. Can someone help me with what is the way of detecting it under the recommendation from apple. Thanks in advance.
Note: checking for replacementString parameter in shouldChangeCharactersIn method for empty does not help for backspace detection as it overlaps with other cases.
We were using below delegate methods from QuickLook to get modified PDF file URL after the sketching But we are not able see the multi line text properly laid out on PDF and part of text missing. Same time Other pencil kit tools are working as expected.
`func previewController(_ controller: QLPreviewController, didSaveEditedCopyOf previewItem: QLPreviewItem, at modifiedContentsURL: URL)
func previewController(_ controller: QLPreviewController, didUpdateContentsOf previewItem: any QLPreviewItem)`
We tested all code in iOS 18.2.
Please let us know if the text edited URL on PDF can be retrieved in any possible way without tampering text
I'm trying to determine if it’s possible to detect when a user interacts with a Slide Over window while my app is running in the background on iPadOS. I've explored lifecycle methods such as scenePhase and various UIApplication notifications (e.g., willResignActiveNotification) to detect focus loss, but these approaches don't seem to capture the event reliably. Has anyone found an alternative solution or workaround for detecting this specific state change? Any insights or recommended practices would be greatly appreciated.
I have to decrease main window screen size when user open Immersive space in my project.
Using frame i try it but it not updated main window size it just update view frame.
A NavigationStack with a singular enum for .navigationDestination() works fine.
Both NavigationLinks(value:) and directly manipulating the NavigationPath work fine for moving around views. Zero problems.
The issue is when we instead use a NavigationSplitView, I've only dabbled with two-column splits (sidebar and detail) so far.
Now, if the sidebar has its own NavigationStack, everything works nicely on an iPhone, but on an iPad, you can't push views onto the detail from the sidebar. (They're pushed on the sidebar)
You can solve this by keeping a NavigationStack ONLY on the detail. Sidebar links now properly push onto the detail, and the detail can move around views by itself.
However, if you mix NavigationLink(value:) with manually changing NavigationPath, it stops working with no error. If you only use links, you're good, if you only change the NavigationPath you're good. Mixing doesn't work. No error in the console either, the breakpoints hit .navigationDestination and the view is returned, but never piled up. (Further attempts do show the NavigationPath is being changed properly, but views aren't changing)
This problem didn't happen when just staying on NavigationStack without a NavigationSplitView.
Why mix? There's a few reasons to do so. NavigationLinks put the appropriate disclosure indicator (can't replicate its look 100% without it), while NavigationPaths let you trigger navigation without user input (.onChange, etc)
Any insights here? I'd put some code samples but there's a metric ton of options I've tested here.
I have a SwiftUI view of the form
struct ContentView: View {
// ...
.onDrop(of: [.pdf], isTargeted: $isDropTargeted) { pdfs in
for pdf in pdfs {
I'm just not sure what to do next, I see there's a loadPreviewImage() that if I use like:
Task.detached {
// returns any NSSecureCoding object
let image = try! await pdf.loadPreviewImage()
}
Not sure how I'm supposed to get my preview image from that NSSecureCoding object
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hello,
I’m developing an app where I display a SwiftUI view inside a UIHostingController embedded within a UIKit ViewController.
I’m trying to animate the height of the UIHostingController’s view based on a switch’s value, but the SwiftUI view doesn’t animate at all.
Below is a simplified version of my code:
class ViewController: UIViewController {
private lazy var parentView: UIView = {
let view = UIView()
view.backgroundColor = .red
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private lazy var hostingView: UIView = {
let testView = TestView()
let hostingController = UIHostingController(rootView: testView)
let view = hostingController.view!
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private lazy var button: UISwitch = {
let button = UISwitch()
button.addTarget(self, action: #selector(onClickSwitch(sender:)), for: .valueChanged)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
private var hostingViewHeightConstraint: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(parentView)
parentView.addSubview(hostingView)
parentView.addSubview(button)
NSLayoutConstraint.activate([
parentView.topAnchor.constraint(equalTo: view.topAnchor),
parentView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
parentView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
parentView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
NSLayoutConstraint.activate([
hostingView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor),
hostingView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor),
hostingView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor)
])
hostingViewHeightConstraint = hostingView.heightAnchor.constraint(equalTo: parentView.heightAnchor, multiplier: 0.5)
hostingViewHeightConstraint?.isActive = true
NSLayoutConstraint.activate([
button.centerXAnchor.constraint(equalTo: parentView.centerXAnchor),
NSLayoutConstraint(item: button,
attribute: .centerY,
relatedBy: .equal,
toItem: parentView,
attribute: .centerY,
multiplier: 0.25,
constant: 0)
])
}
@objc func onClickSwitch(sender: UISwitch) {
hostingViewHeightConstraint?.isActive = false
let multiplier: CGFloat = sender.isOn ? 0.25 : 0.5
hostingViewHeightConstraint = hostingView.heightAnchor.constraint(equalTo: parentView.heightAnchor, multiplier: multiplier)
hostingViewHeightConstraint?.isActive = true
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}
}
I’m looking for the behavior demonstrated in the video below:
Does anyone have suggestions on how to achieve this?
hi does any one know if there changes in lifecycle in xcode 16 ios 18 cause i notice that my view will appear does what view didappear use to do in older version and it kind of a problem cause all the rest of ios work diffrently does anyone else found a problem with it?
or does anyone know if there was a known change to life cycles
I have the MainView as the active view if the user is logged in(authenticated). the memory allocations when we run profile is pretty good. We have graphql fetching, we have token handling eg: This is All heap:
1 All Heap & Anonymous VM 13,90 MiB 65408 308557 99,10 MiB 373965 Ratio: %0.14, %0.86
After what i have checked this is pretty good for initialise and using multiple repositories eg. But when we change tabs:
1 All Heap & Anonymous VM 24,60 MiB 124651 543832 156,17 MiB 668483 Ratio: %0.07, %0.40
And that is not pretty good. So i guess we need to "kill" it or something. How? I have tried some techniques in a forum this was a recommended way:
public struct LazyView<Content: View>: View {
private let build: () -> Content
@State private var isVisible = false
public init(_ build: @escaping () -> Content) {
self.build = build
}
public var body: some View {
build()
Group {
if isVisible {
build()
} else {
Color.clear
}
}
.onAppear { isVisible = true }
.onDisappear { isVisible = false }
}
}
But this did not help at all. So under here is the one i use now. So pleace guide me for making this work.
import DIKit
import CoreKit
import PresentationKit
import DomainKit
public struct MainView: View {
@Injected((any MainViewModelProtocol).self) private var viewModel
private var selectedTabBinding: Binding<MainTab> {
Binding(
get: { viewModel.selectedTab },
set: { viewModel.selectTab($0) }
)
}
public init() {
// No additional setup needed
}
public var body: some View {
NavigationStack(path: Binding(
get: { viewModel.navigationPath },
set: { _ in }
)) {
TabView(selection: selectedTabBinding) {
LazyView {
FeedTabView()
}
.tabItem {
Label("Feed", systemImage: "house")
}
.tag(MainTab.feed)
LazyView {
ChatTabView()
}
.tabItem {
Label("Chat", systemImage: "message")
}
.tag(MainTab.chat)
LazyView {
JobsTabView()
}
.tabItem {
Label("Jobs", systemImage: "briefcase")
}
.tag(MainTab.jobs)
LazyView {
ProfileTabView()
}
.tabItem {
Label("Profile", systemImage: "person")
}
.tag(MainTab.profile)
}
.accentColor(.primary)
.navigationDestination(for: MainNavigationDestination.self) { destination in
switch destination {
case .profile(let userId):
Text("Profile for \(userId)")
case .settings:
Text("Settings")
case .jobDetails(let id):
Text("Job details for \(id)")
case .chatThread(let id):
Text("Chat thread \(id)")
}
}
}
}
}
import SwiftUI
public struct LazyView<Content: View>: View {
private let build: () -> Content
public init(_ build: @escaping () -> Content) {
self.build = build
}
public var body: some View {
build()
}
}
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
Hello, I've managed to get rid of these spaces in different ways. Using scrollview, giving negative insets, rewriting modifiers from scratch with plain style etc. But I couldn't solve this with a simple solution. I've read comments from many people experiencing similar problems online. It seems like there isn't a simple modifier to remove these spaces when we use sidebar as the list style in SwiftUI, or I couldn't find the simple solution.
I wonder what's the simplest and correct way to reset these spaces?
let numbers = Array(1...5)
@State private var selected: Int?
var body: some View {
List(numbers, id: \.self, selection: $selected) { number in
HStack {
Text("Test")
Spacer()
}
.frame(maxWidth: .infinity, alignment: .leading)
}
.listStyle(.sidebar)
}
}
When I present a view controller, whose view is a SwiftUI View, via presentAsModalWindow(_:) the presented window is no longer centered horizontally to the screen, but rather its origin is there. I know this issue occurs for macOS 15.2+, but can't tell if it is from 15.0+. I couldn't find any documentation on why was this changed.
Here's an example code that represents my architecture:
class RootViewController: NSViewController {
private lazy var button: NSButton = NSButton(
title: "Present",
target: self,
action: #selector(presentView))
override func viewDidLoad() {
super.viewDidLoad()
// Add button to tree
}
@objc func presentView() {
presentAsModalWindow(PresentedViewController())
}
}
class PresentedViewController: NSViewController {
override loadView() {
view = NSHostingView(rootView: MyView())
}
}
struct MyView: View {
/* impl */
}
I have received permission from Apple to access SensorKit data for my app. I have granted all necessary permissions, but no data is being retrieved.
The didCompleteFetch method is being called, but I’m unsure where to find event data like Device Usage and Ambient Light. Additionally, the didFetchResult method is never called.
Could anyone please assist me in resolving this issue? Any guidance or troubleshooting steps would be greatly appreciated.
import SensorKit
class ViewController: UIViewController, SRSensorReaderDelegate {
let store = SRSensorReader(sensor: .deviceUsageReport)
override func viewDidLoad() {
super.viewDidLoad()
requestSensorAuthorization()
}
func requestSensorAuthorization() {
var sensors: Set<SRSensor> = [
.accelerometer,
.deviceUsageReport,
.messagesUsageReport,
.visits,
.keyboardMetrics,
.phoneUsageReport,
.ambientLightSensor
]
if #available(iOS 16.4, *) {
sensors.insert(.mediaEvents)
}
SRSensorReader.requestAuthorization(sensors: sensors) { error in
if let error = error {
print("Authorization failed: \(error.localizedDescription)")
} else {
self.store.startRecording()
self.requestSensorData()
print("Authorization granted for requested sensors.")
}
}
}
func requestSensorData() {
let fromTime = SRAbsoluteTime.fromCFAbsoluteTime(_cf: Date().addingTimeInterval(-60 * 60).timeIntervalSinceReferenceDate)
let toTime = SRAbsoluteTime.fromCFAbsoluteTime(_cf: Date().timeIntervalSinceReferenceDate)
let request = SRFetchRequest()
request.from = fromTime
request.to = toTime
request.device = SRDevice.current
store.fetch(request)
store.delegate = self
}
func sensorReader(_ reader: SRSensorReader, didCompleteFetch fetchRequest: SRFetchRequest) {
print("Fetch request completed: \(fetchRequest.from) to \(fetchRequest.to)")
Task {
do {
let samples = try await reader.fetch(fetchRequest)
print("Samples count: \(samples)")
} catch {
print("Error Fetching Data: \(error.localizedDescription)")
}
}
}
func sensorReader(_ reader: SRSensorReader, fetching fetchRequest: SRFetchRequest, didFetchResult result: SRFetchResult<AnyObject>) -> Bool {
print(result)
return true
}
}
Hello,
I am currently encountering an issue where SwiftUI View Previews cannot be displayed when the View is defined in a Static Framework target. This issue only occurs under specific conditions.
Environment
Xcode: 16.2
Scheme Structure:
MainApp
Test Target: TestHogeFeature
Test Setting:
Gather coverage (Code coverage collection) enabled(all)
Target Structure:
MainApp (Application target)
Dependencies: [HogeFeature, Core]
HogeFeature (Static Framework target)
Dependencies: [Core]
Core (Framework target)
Dependencies: None
TestHogeFeature (Unit test target)
Dependencies: [HogeFeature]
Summary
I am currently working on a SwiftUI-based project and have encountered an issue where Previews fail to display under specific conditions. Below are the details:
Issue
In the MainApp scheme, when the code coverage collection setting (Gather coverage for) is enabled, Previews for SwiftUI Views within the HogeFeature (Static Framework) target fail to display correctly. However, the issue is resolved by taking one of the following actions:
Change HogeFeature from a Static Framework to a Dynamic Framework.
Remove the build setting MACH_O_TYPE: staticlib
Disable the Gather coverage setting in the MainApp scheme.
I have attached the actual error log from the failed Preview.
preview error log
Questions
Why does this issue occur only when using a Static Framework with code coverage enabled?
Is there any way to resolve this issue while maintaining the current configuration (Static Framework with code coverage enabled)?
I would appreciate any advice or insights regarding the cause and potential solutions.
Hi,
I’m practicing with NavigationSplitView for macOS and customizing the sidebar. I’ve managed to adjust most parts, but I couldn’t remove the sidebar’s divider. It seems like it’s not possible in modern SwiftUI. My AppKit knowledge is also not very strong.
How can I remove the sidebar divider?
I want to use a plain background. I also solved it by creating my own sidebar, but I wanted to try it using NavigationSplitView.