My SwiftData model doesn't have time to update, and the widget gets old data on the timeline
I create simple SwiftData app with widget extension. To share swiftdata between widget and app I use the same approach as in sample code "Adopting SwiftData for a Core Data app":
let modelContext = ModelContext(DataModel.shared.modelContainer)
if let models = try? modelContext.fetch(fetchDescriptor) {
// use
}
After I create/delete/updated model I call:
WidgetCenter.shared.reloadAllTimelines()
The problem is that the widget receives outdated data as a result of modelContext.fetch. To get the new data I need to call WidgetCenter.shared.reloadAllTimelines() twice or with some delay:
// MyModelEditorView
private func save() {
if let myModel {
myModel.title = title
} else {
let myModel = MyModel(
title: title
)
modelContext.insert(word)
}
WidgetCenter.shared.reloadAllTimelines()
// i have to call it twice
WidgetCenter.shared.reloadAllTimelines()
}
I couldn't test SampleCode for similar update behavior, because somehow I couldn't get the models into the widget and I only have "No Trip" displayed there.
If I remove the second call, the UI is updated immediately and the new title is displayed, but the widget in the timeline receive the old title.
I don't understand whether this is the case and I need to update the widget with a delay or am I doing something wrong?
BTW:
Why is sample code in init we don't use shared container?
private let modelContainer: ModelContainer
init() {
do {
// why we don't use DataModel.shared.modelContainer
modelContainer = try ModelContainer(for: Trip.self)
} catch {
fatalError("Failed to create the model container: \(error)")
}
}
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
Crashed: com.apple.root.user-initiated-qos.cooperative
0 Foundation 0x4e2a4 specialized String.withUTF8(:) + 100
1 Foundation 0x4eb8c JSONWriter.serializeString(:) + 100
2 Foundation 0x4e810 JSONWriter.serializeJSON(:depth:) + 92
3 Foundation 0x4cfd4 JSONWriter.serializeObject(:depth:) + 888
4 Foundation 0x4e914 JSONWriter.serializeJSON(:depth:) + 352
5 Foundation 0xd06fc JSONEncoder.encode(:) + 624
6 Foundation 0xd0484 dispatch thunk of JSONEncoder.encode(_:) + 56
I am experimenting with drag-and-drop on iPadOS.
If I drag a JPEG image from a webpage in Safari to my app, I get items of types public.jpeg and public.url.
Typically, the URL is the URL of the image.
If, however, the image is itself a link, then the URL seems to be the target of the link.
Is there some way that I can always get the URL of the image itself? Is there some way that I can determine whether the URL I have received is the URL of the image or of a link?
Hi, I notice a very slow transfer rate when I try to transfer a file picked via .photosPicker. This happens especially when I try to import a 4k/60fps video.
SwiftUI:
VStack {
Button("Pick a video") {
model.isPhotoPickerView = true
}
.photosPicker(isPresented: $model.isPhotoPickerView, selection: $model.selectedImageList, maxSelectionCount: 1, matching: .videos)
.onChange(of: model.selectedImageList, { old, new in
model.handlePhotoPicker()
})
}
View Model to handle Photo Picker action:
private class PageModel: ObservableObject {
//other methods
@MainActor
public func handlePhotoPicker() {
if selectedImageList.isEmpty {
return
}
guard let item = selectedImageList.first else {
return
}
Task {
do {
if let video = try await item.loadTransferable(type: VideoTransferable.self) {
let file = video.url
//video url arrived
}
} catch {
//handle error
}
}
}
}
Now the VideoTransferable :
struct VideoTransferable: Transferable {
let url: URL
static var transferRepresentation: some TransferRepresentation {
FileRepresentation(contentType: .movie) { video in
SentTransferredFile(video.url)
}
importing: { received in
//takes too much time to import large 4K video recorded from iPhone's main camera
let copy = FileManager.documentsDirectory.appendingPathComponent(FolderType.temp.rawValue).appendingPathComponent("video_\(Int64(Date().timeIntervalSince1970 * 1000)).MOV")
if FileManager.default.fileExists(atPath: copy.path) {
try FileManager.default.removeItem(at: copy)
}
try FileManager.default.copyItem(at: received.file, to: copy)
return Self.init(url: copy)
}
}
}
To my surprise this issue doesn't happen when I use a custom UIViewControllerRepresentable to wrap UIImagePickerController() and setting videoExportPreset property of the picker to AVAssetExportPresetPassthrough
Can someone point me out where I am wrong?
Hey, I have a use case where I want to show a tip for a menu thats in a toolbar. Here's my approach to attach the tip to the Menu. I also tried to attach it to the Button in the menu but in both cases the tip was not shown.
None of the described fixes in this post worked for me, adding .buttonStyle(.borderless) didn't help either ...
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Menu {
Button {
// ...
} label: {
// ...
}
} label: {
Image(systemName: "heart")
}
.popoverTip(Tip())
}
}
I'm working on a visionOS app
In iOS18, Not able to use the UITabBarControllerDelegate.tabBarController(:didSelectTab:previousTab:) function. Since it have duplicate parameter name for didselectTab and previousTab , we're getting Invalid redeclaration of 'tab' error.
Hi Team,
We are facing crash in CAMediaTimingCopyRenderTiming for production users. And we are unable to trace the crash.
Below is the crash stack trace -
Crashed: com.apple.main-thread
0 QuartzCore 0x14b9c CAMediaTimingCopyRenderTiming + 660
1 QuartzCore 0xfa9c -[CAAnimation _setCARenderAnimation:layer:] + 64
2 QuartzCore 0x146e4 -[CAAnimationGroup _copyRenderAnimationForLayer:] + 356
3 QuartzCore 0x12f3c CA::Layer::commit_animations(CA::Transaction*, double ()(CA::Layer, double, void*), void ()(CA::Layer, CA::Render::Animation*, void*), void ()(CA::Layer, __CFString const*, void*), CA::Render::TimingList* ()(CA::Layer, void*), void*) + 688
4 QuartzCore 0x277c invocation function for block in CA::Context::commit_transaction(CA::Transaction*, double, double*) + 176
5 QuartzCore 0x482bc CA::Layer::commit_if_needed(CA::Transaction*, void (CA::Layer*, unsigned int, unsigned int) block_pointer) + 384
6 QuartzCore 0x48244 CA::Layer::commit_if_needed(CA::Transaction*, void (CA::Layer*, unsigned int, unsigned int) block_pointer) + 264
7 QuartzCore 0x48244 CA::Layer::commit_if_needed(CA::Transaction*, void (CA::Layer*, unsigned int, unsigned int) block_pointer) + 264
8 QuartzCore 0x48244 CA::Layer::commit_if_needed(CA::Transaction*, void (CA::Layer*, unsigned int, unsigned int) block_pointer) + 264
9 QuartzCore 0x48244 CA::Layer::commit_if_needed(CA::Transaction*, void (CA::Layer*, unsigned int, unsigned int) block_pointer) + 264
10 QuartzCore 0x48244 CA::Layer::commit_if_needed(CA::Transaction*, void (CA::Layer*, unsigned int, unsigned int) block_pointer) + 264
11 QuartzCore 0x48244 CA::Layer::commit_if_needed(CA::Transaction*, void (CA::Layer*, unsigned int, unsigned int) block_pointer) + 264
12 QuartzCore 0x48244 CA::Layer::commit_if_needed(CA::Transaction*, void (CA::Layer*, unsigned int, unsigned int) block_pointer) + 264
13 QuartzCore 0x48244 CA::Layer::commit_if_needed(CA::Transaction*, void (CA::Layer*, unsigned int, unsigned int) block_pointer) + 264
14 QuartzCore 0x48244 CA::Layer::commit_if_needed(CA::Transaction*, void (CA::Layer*, unsigned int, unsigned int) block_pointer) + 264
15 QuartzCore 0x48244 CA::Layer::commit_if_needed(CA::Transaction*, void (CA::Layer*, unsigned int, unsigned int) block_pointer) + 264
16 QuartzCore 0x2e078 CA::Context::commit_transaction(CA::Transaction*, double, double*) + 6224
17 QuartzCore 0x59dc0 CA::Transaction::commit() + 644
18 QuartzCore 0x44dbc CA::Transaction::flush_as_runloop_observer(bool) + 84
19 CoreFoundation 0x898e8 CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 32
20 CoreFoundation 0x1951c __CFRunLoopDoObservers + 552
21 CoreFoundation 0x75214 __CFRunLoopRun + 1004
22 CoreFoundation 0x79d20 CFRunLoopRunSpecific + 584
23 GraphicsServices 0x1998 GSEventRunModal + 160
24 UIKitCore 0x371448 -[UIApplication _run] + 868
25 UIKitCore 0x3710c0 UIApplicationMain + 312
26 SwiftUI 0x183c68 OUTLINED_FUNCTION_895 + 2184
27 SwiftUI 0xfdf1c block_copy_helper.1 + 452
28 SwiftUI 0xeaf6c OUTLINED_FUNCTION_901 + 2312
29 Evie Ring 0x2dd20c main + 10 (MovanoRingApp.swift:10)
30 ??? 0x1c7724344 (Missing)
I have an URGENT assignment with detail as below:
I have an application and it has an Extension UI for it.
When I select an item of popup list on standard UI of application.
How can I catch event of this selection in standard UI and do update for Extension UI?
Do we have any relationship between Standard UI and Extension UI in MacOS?
Please help to share your experience about this technical?
I have some key commands registered in Responder chain on IOS application that reacts to F1-F12 keys. I have bluetooth keyboard connected to ipad that has some default functions assigned to most of F keys and because of that my application doesn't react when i click F key and fires the default behaviour.
For example i have callback registered on F1 key that has default function of dimming the screen. When i click F1 key the screen is dimmed and the callback is not fired.
When i click on F5 which does not have any default function the callback is called properly.
How can i disable this default behaviour or somehow make my application react to FKeys?
Keyboard model: A1644
Ipad 6
This problem will occur in Xcode 16 beta and iOS 18 beta, are there any changes to the function of highPriorityGesture in iOS 18?
Example code is:
import SwiftUI
struct ContentView: View {
@State private var dragable: Bool = false
@State private var dragGestureOffset: CGFloat = 0
var body: some View {
ZStack {
ScrollViewReader { scrollViewProxy in
ScrollView(showsIndicators: false) {
cardList
.padding(.horizontal, 25)
}
}
}
.highPriorityGesture(dragOffset)
}
var cardList: some View {
LazyVStack(spacing: 16) {
Text("\(dragGestureOffset)")
.frame(maxWidth: .infinity)
.padding(.vertical,8)
.background {
RoundedRectangle(cornerRadius: 8)
.fill(.gray)
}
//Display 100 numerical values in a loop
ForEach(0..<100) { index in
Text("\(index)")
.frame(maxWidth: .infinity)
.padding(.vertical,8)
.background {
RoundedRectangle(cornerRadius: 8)
.fill(.gray)
}
}
}
}
var dragOffset: some Gesture {
DragGesture()
.onChanged { value in
if abs(value.translation.width) > 25 {
dragable = true
dragGestureOffset = value.translation.width
}
}
.onEnded { value in
if abs(value.translation.width) > 25 {
dragable = false
dragGestureOffset = 0
}
}
}
}
i use @Observable
@Observable
class TextClass {
var text: String = ""
}
@State
struct ContentView: View {
@State var text: TextClass = .init()
var body: some View {
Form {
Text(text.text)
Button("upup") {
text.text += "1"
}
}
Form {
ChildView(text: text)
}
}
}
struct ChildView: View {
@State var text: TextClass
var body: some View {
Text (text.text)
Button("upup Child") {
text.text += "2"
}
}
}
@Binding
struct ContentView: View {
@State var text: TextClass = .init()
var body: some View {
Form {
Text(text.text)
Button("upup") {
text.text += "1"
}
}
Form {
ChildView(text: $text)
}
}
}
struct ChildView: View {
@Binding var text: TextClass
var body: some View {
Text (text.text)
Button("upup Child") {
text.text += "2"
}
}
}
@Bindable
struct ContentView: View {
@State var text: TextClass = .init()
var body: some View {
Form {
Text(text.text)
Button("upup") {
text.text += "1"
}
}
Form {
ChildView(text: text)
}
}
}
struct ChildView: View {
@Bindable var text: TextClass
var body: some View {
Text (text.text)
Button("upup Child") {
text.text += "2"
}
}
}
What are the differences between @State, @Binding, and @Bindable, all of which function similarly for bidirectional binding? Which one should I use?
I'm curious about the differences between the three.
onContinueUserActivity(CSSearchableItemActionType, perform) works as expected on iOS when we search and select an item from Spotlight, but nothing happens when we do the same on a SwiftUI macOS app.
var body: some Scene {
WindowGroup {
MyView()
.onContinueUserActivity(CSSearchableItemActionType, perform: handleSpotlight)
}
}
func handleSpotlight(_ userActivity: NSUserActivity) {
// Is not called...
}
How can we respond to a user clicking a Spotlight result from our apps on macOS?
Hi everyone,
Like so many before me, i tried to install my app to test widgets, live activities & dynamic island implementation on a real device or on the simulator (neither works). The problem is that when I try to run the project I get this message :
"SendProcessControlEvent:toPid: encountered an error: Error Domain=com.apple.dt.deviceprocesscontrolservice Code=8 "Failed to show Widget 'fr.example.LiveActivities.LiveWidget' error: Error Domain=FBSOpenApplicationServiceErrorDomain Code=1 "The request to open "com.apple.springboard" failed." UserInfo={NSLocalizedFailureReason=The request was denied by service delegate (SBMainWorkspace).
[......]".
The first thing I tried was looking on Apple's forum and StackOverflow for a solution but after 1hour trying almost eveyrthing, nothing seemed to resolve my problem.
Does anyone has an idea of how I could try to fix it ? I would love to show this project in my portfolio in order to find an apprenticeship, but I can't until I find a way to fix this.
Thanks a lot!
I can intercept the "Return" button and "Shift+Return" on an iPad's external Bluetooth keyboard with the TextField "onKeyPress" method. But - this always dismisses the keyboard. It looks like the TextField loses focus. This happens whether I return ".handled" or ".ignored".
How can I maintain focus on the TextField and not have the keyboard dismissed?
The SF Symbols app 6.0 (99) does not export the ‘Can Rotate’ property of layers when exporting a symbol via File > Export Symbol.
Without this, all the new fantastic edit functions in the app related to rotating in SF Symbols is completely useless.
This issue with the SF Symbols 6 app can be reproduced by exporting a rotatable symbol like fan.desk, and then by importing the result as custom symbol. When inspecting ‘Group 1’ of the imported symbol, it is no longer marked as rotatable.
SF Symbols app 6.0 is still in beta, but hasn't been updated since 10 June. Hopefully this bug will be solved in the release version, or earlier.
Does anyone know how to manually add the missing rotation info to the exported SVG file?
In case an Apple engineer reads this: FB13916635
After experiencing the official demo (https://developer.apple.com/documentation/visionos/destination-video) on a real device and a demo, I tried to change the poster of the to-be-played list displayed by customOverlayViewController in the demo to a VStack layout. The poster in customOverlayViewController could not fully respond to click events.
I found a very strange bug while using SwiftUI, and the following code is the minimum required to reproduce it.
When I press the 'Go to page2' button, the CPU load goes to 100% and the memory usage keeps increasing. What's wrong with this code?
I tried to search for a day but could not find any answer.
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationStack {
Page1()
.environmentObject(Foo())
}
}
}
class Foo: ObservableObject {
init() {}
}
struct Page1: View {
u/EnvironmentObject
private var viewModel: Foo
u/Binding
var value: Int
init() {
self._value = .init(get: { 0 }, set: { _ in })
}
u/State
private var id: UUID? = nil
var body: some View {
NavigationLink(value: 0) {
Text("Go to page2")
.padding()
.foregroundStyle(.white)
.background(.black)
.cornerRadius(12)
}
.navigationDestination(for: Int.self) { _ in
Page2(
onComplete: {
print("value", value)
}
)
}
}
}
struct Page2: View {
public init(onComplete _: u/escaping () -> Void) {}
public var body: some View {
Text("This is Page2")
.task {
print("hi")
}
}
}
ViewControllers for the 8th and higher tabs are not displayed in the elevated Tab Bar. However, I am able to select these tabs both in the Tab Bar and the side bar.
func setTabs(){
let colors = [UIColor.red,.systemGray6,.green,.systemMint,.cyan,.yellow,.blue,.magenta]
var tabs = [UITab]()
let range = 0...10
for index in range {
if #available(iOS 18.0, *) {
let tab = UITab(title: "Tab_\(index)", image: UIImage(systemName: "globe"), identifier: "tab__\(index)", viewControllerProvider: {tab in
let vc = UIViewController()
vc.view.backgroundColor = colors[index%colors.count]
return vc
})
tabs.append(tab)
}
}
tabbarController.setTabs(tabs, animated: true)
}
Hi , I am new to SwiftUI and Mac/iOS concepts so am on a very steep learning curve.
If this is not the correct forum for this please let me know and I will delete and post elsewhere ...
Basically I am doing a favor for a friend and writing a simple data collection app for his iPad in Swift... it consists of a quite long list list of items to select from, each of which will have several possible values. Clicking on a "Change" button next to each item will bring up a list of possible values to choose from. So ....
The code works except that the list is displayed as an "icon" and has to be clicked to display the items to choose from ...
**How do I get the list to display automatically when instanced without having to click on the List icon ? **
Code: I have a list view which is called as the result of a button press:
Button(action: {
isShowingList=true
When the View is refreshed (State variable) results in the Selectable List view as follows:
struct TechReportView: View {
@State private var isShowingList = false
var body: some View {
if isShowingList { // display a selectable list
SelectableListView(selectedItem: $selectedItem,
isShowingList: $isShowingList,
items: $copyList,
)
}
else
{ // show list of items and current values}
The List View is as follows
struct SelectableListView: View {
@Binding var selectedItem: String?
@Binding var isShowingList: Bool
@Binding var items : [String]
var key : String
@Binding var toChange : String
var body: some View {
VStack()
{
NavigationView {
List(items, id: \.self) { item in
HStack {
Text(item)
Spacer()
if item == selectedItem {
Image(systemName: "checkmark")
.foregroundColor(.blue)
}
}
.contentShape(Rectangle())
.onTapGesture {
selectedItem = item
toChange = item
isShowingList = false
setSKeyData(key, selectedItem!)
}
}
.navigationTitle("Select Item")
.navigationBarItems(trailing: Button("Cancel") {
isShowingList = false
})
}
}
}
}
Hello my appclip is showing as unavailable in the app clip card. Until earlier this afternoon my appclip experience was showing correctly with an open action. All of a sudden it started to fail. I did not submit a new version nor updated the association file.
To reproduce scan qr.netflix.com/C/123