We have a feature requirement where we need to use LazyVGrid and DropDelegate. Our view hierarchy is as follows:
Color.white.ignoresSafeArea()
VStack(spacing: 0) {
customNavigationView
ScrollView(showsIndicators: true) {
LazyVGrid(columns: columns,
alignment: .center,
spacing: 16) {
ForEach(viewModel.selectedReferences, id: \.self) { item in
ZStack {
Rectangle()
.fill(Color.yellow.opacity(0.5))
Text(item.title)
}
.frame (height: 120)
.background(Color.white)
.padding([.leading, .trailing], 4)
.overlay((draggedItem?.uuid == item.uuid && changedView) ? Color.white.opacity(0.8) : Color.clear)
.clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
.onDrag {
initialIndex = viewModel.selectedReferences.firstIndex { $0 == item }
draggedItem = item
changedView = false
return NSItemProvider(object: String(item.uuid) as NSString)
}
.clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
.onDrop(of: [UTType.text], delegate: DragRelocateDelegate(item: item,
listData: $viewModel.selectedReferences,
current: $draggedItem,
changedView: $changedView) { endIndex in
})
}
}
.animation(.default, value: viewModel.selectedReferences)
}
.frame(width:(UIScreen.main.bounds.width))
.onDrop(of: [UTType.text], delegate: DropOutsideDelegate(current: $draggedItem, changedView: $changedView))
bottomBarView
}
.frame(maxWidth: .infinity)
}
While performing a reshuffle, auto-scroll works within the bounds of the ScrollView content. However, according to the feature requirement, auto-scroll should also work when we place an uplifted view at the top or bottom of the view.
STEPS TO REPRODUCE
Launch the demo.
Scroll to the bottom of the LazyVGrid.
Pick any item using the DropDelegate.
Try to place that uplifted view on the custom navigation view.
Expected Result:
The ScrollView should auto-scroll.
Actual Result:
Auto-scroll is not working.
Dive into the world of programming languages used for app development.
Post
Replies
Boosts
Views
Activity
White-label messaging is like a pre-made chat app that one company creates, but other companies can make it look like it’s their own by changing its appearance and name. Basically, it’s a chat tool that businesses can buy and use with their own branding.
Hello we have created a function that is expanding copy module to support html format. Everything inside that function works fine but on 17.4+ IOS version copying the html element strike-through tag is not working (other HTML elements are working fine) . Looking the logs seems like are getting stripped.
Here is the code:
void copyToClipboard(NSString *htmlContent) {
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
[pasteboard setValue:htmlContent forPasteboardType:@"public.html"];
}
Does anyone know fix for this or when this will be fixed or will it be fixed in next update?
In my case, I open an immersiveSpace and windowGroupA together. When I successfully push a new windowGroupB from windowGroupA, dismissing windowGroupB should return me to windowGroupA. However, this fails, and windowGroupA remains in the background scenePhase. I tried closing immersiveSpace, and it worked successfully. Therefore, pushWindow cannot be used when immersiveSpace is open.
Hi, i am currently updating my app in SwiftUI from iOS 16.4 to 18.0, i am getting in xcode these new warning
@State' used inline will not work unless tagged with '@Previewable'
so i fix the problem with the suggestions and add the new tag @Previewable and put the variable in the first line of the preview
#Preview {
@Previewable @State var enabled: Bool = true
return NotificationLabel(enabled: $enabled, type: "test", icon: "star", title: "test", description: "test")
}
the problem is that my app is available from iOS 16.4 to iOS 18.0 and the preview gives me this error
'Previewable()' is only available in iOS 18.0 or newer
but if i put a versione if at the top i get another error
if #available(iOS 18.0, *){
@Previewable @State var enabled: Bool = true
@Previewable' items must be at root scope in the preview block
is there a way to silence the warning making a two version preview, one for iOS 18 and one for the previous versions?
I have a punycode link of the following type: https://xn--d1aqf.xn--p1ai/.However, clicking on this link, or opening it through the simulator, opens the page in the browser, not in the application. The system does not see that this domain is present in one of the applications, however, any other domain (example.com , for example), is validated by the system. What could this be related to?
Hi Team,
I am having use case where I need to validate/ compare a date received from server with local date.
For example
I received date from the server is 30th June 2024
And
I need to compare the server date is greater than today's date or not.
Based on this, I need to allow user to continue access of feature.
But iphone user can change the date time of device from iphone's setting option. For example from today to previous month date. So when I tried to compare the server date which I have stored locally is always ahead of today.
I can not fetch date from server again and again.
How do I get exactly real date even though user has changed device date without fetching from any server?
Actually, I'm developing a new app based on screen time API, so I implemented my report device extension like this
struct TotalActivityReport: DeviceActivityReportScene {
// Define which context your scene will represent.
let context: DeviceActivityReport.Context = .totalActivity
// Define the custom configuration and the resulting view for this report.
let content: (ActivityReport) -> TotalActivityView
func makeConfiguration(representing data: DeviceActivityResults<DeviceActivityData>) async -> ActivityReport {
// Reformat the data into a configuration that can be used to create
// the report's view.
var res = ""
var list: [AppDeviceActivity] = []
let totalActivityDuration = await data.flatMap { $0.activitySegments }.reduce(0, {
$0 + $1.totalActivityDuration
})
for await d in data {
res += d.user.appleID!.debugDescription
res += d.lastUpdatedDate.description
for await a in d.activitySegments{
res += a.totalActivityDuration.formatted()
for await c in a.categories {
for await ap in c.applications {
let appName = (ap.application.localizedDisplayName ?? "nil")
let bundle = (ap.application.bundleIdentifier ?? "nil")
let duration = ap.totalActivityDuration
let numberOfPickups = ap.numberOfPickups
let token = ap.application.token
let app = AppDeviceActivity(
id: bundle,
displayName: appName,
duration: duration,
numberOfPickups: numberOfPickups,
token: token
)
list.append(app)
}
}
}
}
return ActivityReport(totalDuration: totalActivityDuration, apps: list)
}
}
Then TotalActivityView to visualize returned data like this
//
// TotalActivityView.swift
// DemoScreenTimeReporter
//
// Created by Achraf Trabelsi on 17/06/2024.
//
import SwiftUI
import ManagedSettings
struct TotalActivityView: View {
var activityReport: ActivityReport
var body: some View {
VStack {
Spacer(minLength: 50)
Text("Total Screen Time")
Spacer(minLength: 10)
Text(activityReport.totalDuration.stringFromTimeInterval())
List(activityReport.apps) { app in
ListRow(eachApp: app)
}
}
}
}
struct ListRow: View {
var eachApp: AppDeviceActivity
var body: some View {
HStack {
Text(eachApp.displayName)
Spacer()
Text(eachApp.id)
Spacer()
Text("\(eachApp.numberOfPickups)")
Spacer()
Text(String(eachApp.duration.formatted()))
if let appToken = eachApp.token {
Label(appToken).labelStyle(.iconOnly)
}
}
}
}
But I got this issue : Cannot convert value of type 'ApplicationToken' (aka 'Token') to expected argument type 'LabelStyleConfiguration'
So if anyone have an idea, how can we get application icons please ?
I have a DatePicker in View not Viewcontroller.
The solution in stack overflow works fine, if the DatePicker is in ViewController.
(https://stackoverflow.com/questions/67109078/close-uidatepicker-after-selection-when-style-is-compact)
I want to close DatePIcker after selecting a date.
Thank you.
FB13955415
Calls to openURL in iOS 18 beta 22A5282m fails to launch browser.
Is this a bug?
Hello,
We've a music app reading MPMediaItem.
We got items using MPMediaQuery. But we realized that some downloaded tracks from Apple Music were fetched too. Not all downloaded track but only those who were played recently.
Of course, since these tracks are protected with DRM we can't play them in our player.
It's weird to get them in our query because we added predicate in order to dont fetch protected asset and iCloud item
MPMediaPropertyPredicate(value: false, forProperty: MPMediaItemPropertyHasProtectedAsset)
MPMediaPropertyPredicate(value: false, forProperty: MPMediaItemPropertyIsCloudItem)
To be sure, we made a second check on each item we've fetched
extension MPMediaItem {
public func isValid() -> Bool {
return self.assetURL != nil && !self.isCloudItem && !self.hasProtectedAsset
}
}
But we still get these items. Their hasProtectedAsset attribute always return false.
I dont know if it's a bug, but since we can't detect this items as Apple Music downloaded track, we can't either:
filter them to not add them in our application library
OR
switch on a MPMusicPlayerController.applicationMusicPlayer to allow the user to play them
Hi everyone,
I'm working on a Vision Pro application and encountering an issue while trying to load a USDZ file. Here are the details:
File Path:
/Users/siddharthpatel/Library/Developer/CoreSimulator/Devices/31F10013-50B6-4CEF-9388-9094087FAEBF/data/Containers/Data/Application/EB260F0A-A84F-4E95-876D-08199D2A4998/Documents/hive1.usdz
Code:
do {
try await modelEntityForCollider = ModelEntity(contentsOf: fileURL!)
} catch {
print("Error loading model: (error)")
}
Error:
Thread 1: Fatal error: Failed to import entity from "/Users/siddharthpatel/Library/Developer/CoreSimulator/Devices/31F10013-50B6-4CEF-9388-9094087FAEBF/data/Containers/Data/ ... ve1.usdz"
I've verified that the file path is correct and the USDZ file exists at the specified location. What could be causing this error and how can I resolve it?
Thanks in advance for your help!
Siddharth
I'm trying to get the url out of a binary webloc file, but I'm getting the follow error:
NSURLConnection finished with error - code -1002.
error: The file “link.webloc” couldn’t be opened.
Does anyone know how to read a binary webloc file with swift?
func readFile() {
if let path = Bundle.main.path(forResource: "link", ofType: "webloc") {
print("path: \(path)")
if let url = URL(string: path) {
do {
let data = try Data(contentsOf: url)
let plist = try PropertyListSerialization.propertyList(from: data, options: [], format: nil)
print("plist")
} catch {
print("error: \(error.localizedDescription)")
}
}
}
}
I made a git repo of the project if anyone want to try it out.
https://github.com/syclonefx/ReadWeblocFile.
I have 2 different webloc files the link.webloc is a binary webloc file and the link2.webloc is a text webloc file
CrashLog
Distributor ID: com.apple.AppStore
Hardware Model: iPhone15,3
Process: DeadLineTodo [5556]
Path: /private/var/containers/Bundle/Application/348CC8D5-05FD-41DF-93A3-C15562EF4AA8/DeadLineTodo.app/DeadLineTodo
Identifier: andy.DeadLineTodo
Version: 2.4.0 (3)
AppStoreTools: 15F31e
AppVariant: 1:iPhone15,3:17
Code Type: ARM-64 (Native)
Role: Foreground
Parent Process: launchd [1]
Coalition: andy.DeadLineTodo [2089]
Date/Time: 2024-06-08 19:13:53.6259 +0800
Launch Time: 2024-06-08 19:13:53.2839 +0800
OS Version: iPhone OS 17.5.1 (21F90)
Release Type: User
Baseband Version: 2.60.02
Report Version: 104
Exception Type: EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x0000000195a2d8c0
Termination Reason: SIGNAL 5 Trace/BPT trap: 5
Terminating Process: exc handler [5556]
Triggered by Thread: 0
Thread 0 name:
Thread 0 Crashed:
0 libswiftCore.dylib 0x0000000195a2d8c0 _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:144)
1 DeadLineTodo 0x0000000100dde700 DeadLineTodoApp.init() + 1140 (DeadLineTodoApp.swift:46)
2 DeadLineTodo 0x0000000100ddef30 protocol witness for App.init() in conformance DeadLineTodoApp + 28 (<compiler-generated>:0)
3 SwiftUI 0x000000019b2c84c0 static App.main() + 116 (App.swift:114)
4 DeadLineTodo 0x0000000100ddeec4 static DeadLineTodoApp.$main() + 40 (<compiler-generated>:0)
5 DeadLineTodo 0x0000000100ddef5c main + 12 (DeadLineTodoApp.swift:32)
6 dyld 0x00000001ba7d1e4c start + 2240 (dyldMain.cpp:1298)
Thread 1:
0 libsystem_pthread.dylib 0x00000001f3fa40c4 start_wqthread + 0 (:-1)
Thread 2:
0 libsystem_pthread.dylib 0x00000001f3fa40c4 start_wqthread + 0 (:-1)
Thread 0 crashed with ARM Thread State (64-bit):
x0: 0x8000000100f01ad0 x1: 0x0000000000000000 x2: 0x0000000000000000 x3: 0x00000003019e9bc0
x4: 0x0000000000000000 x5: 0x000000016f16f3e0 x6: 0x000000000000002e x7: 0x0000000000000000
x8: 0x0000000000000100 x9: 0x00000000000000ff x10: 0x0000000000001b80 x11: 0x00000000f3444870
x12: 0x00000000000007fb x13: 0x00000000000007fd x14: 0x00000000f364506f x15: 0x000000000000006f
x16: 0x00000000f3444870 x17: 0x0000000000045000 x18: 0x0000000000000000 x19: 0x0000000100f01dba
x20: 0x8000000100f01ad0 x21: 0x0000000000000000 x22: 0x000000000000000b x23: 0x0000000000000022
x24: 0x000000000000002e x25: 0x0000000100f01ac0 x26: 0xd000000000000025 x27: 0x0000000000000000
x28: 0x0000000000000000 fp: 0x000000016f16f5c0 lr: 0x0000000195a2d8c0
sp: 0x000000016f16f4f0 pc: 0x0000000195a2d8c0 cpsr: 0x60001000
esr: 0xf2000001 (Breakpoint) brk 1
Binary Images:
0x100c90000 - 0x100f0ffff DeadLineTodo arm64 <c16650393d4537299a08b798b8227d31> /private/var/containers/Bundle/Application/348CC8D5-05FD-41DF-93A3-C15562EF4AA8/DeadLineTodo.app/DeadLineTodo
0x101214000 - 0x10121ffff libobjc-trampolines.dylib arm64e <2e2c05f8377a30899ad91926d284dd03> /private/preboot/Cryptexes/OS/usr/lib/libobjc-trampolines.dylib
0x1959f4000 - 0x195f43fff libswiftCore.dylib arm64e <d9ad5cc1ca2c3f0a8091652b0df56d14> /usr/lib/swift/libswiftCore.dylib
0x19af1c000 - 0x19ccbafff SwiftUI arm64e <c1325fda9da239d2ab83a338b4d8a884> /System/Library/Frameworks/SwiftUI.framework/SwiftUI
0x1ba795000 - 0x1ba821ef7 dyld arm64e <71846eacee653697bf7d790b6a07dcdb> /usr/lib/dyld
0x1f3fa3000 - 0x1f3fafff3 libsystem_pthread.dylib arm64e <1196b6c3333d3450818ff3663484b8eb> /usr/lib/system/libsystem_pthread.dylib
EOF
DeadLineTodoApp.swift
import SwiftUI
import SwiftData
typealias TodoData = TodoDataSchemaV8.TodoData
typealias UserSetting = TodoDataSchemaV8.UserSetting
enum TodoDataMigrationPlan: SchemaMigrationPlan {
static var schemas: [VersionedSchema.Type] {
[TodoDataSchemaV1.self, TodoDataSchemaV2.self, TodoDataSchemaV3.self, TodoDataSchemaV4.self, TodoDataSchemaV5.self, TodoDataSchemaV6.self, TodoDataSchemaV7.self, TodoDataSchemaV8.self]
}
static var stages: [MigrationStage]{
[migrationV1toV2, migrationV2toV3, migrationV3toV4, migrationV4toV5, migrationV5toV6, migrationV6toV7, migrationV7toV8]
}
static let migrationV1toV2 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV1.self, toVersion: TodoDataSchemaV2.self)
static let migrationV2toV3 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV2.self, toVersion: TodoDataSchemaV3.self)
static let migrationV3toV4 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV3.self, toVersion: TodoDataSchemaV4.self)
static let migrationV4toV5 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV4.self, toVersion: TodoDataSchemaV5.self)
static let migrationV5toV6 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV5.self, toVersion: TodoDataSchemaV6.self)
static let migrationV6toV7 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV6.self, toVersion: TodoDataSchemaV7.self)
static let migrationV7toV8 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV7.self, toVersion: TodoDataSchemaV8.self)
}
@main
struct DeadLineTodoApp: App {
let container: ModelContainer
@StateObject var store = StoreKitManager()
@State var updated: Bool = false
init() {
do {
container = try ModelContainer(
for: TodoData.self, UserSetting.self,
migrationPlan: TodoDataMigrationPlan.self)
} catch {
print("初始化模型容器时发生错误:\(error)")
fatalError("Failed to initialize model container.")
}
}
var body: some Scene {
WindowGroup {
ContentView(updated: $updated)
.environmentObject(store)
}
.modelContainer(container)
}
}
Distributor ID: com.apple.AppStore
Hardware Model: iPhone15,3
Process: DeadLineTodo [5556]
Path: /private/var/containers/Bundle/Application/348CC8D5-05FD-41DF-93A3-C15562EF4AA8/DeadLineTodo.app/DeadLineTodo
Identifier: andy.DeadLineTodo
Version: 2.4.0 (3)
AppStoreTools: 15F31e
AppVariant: 1:iPhone15,3:17
Code Type: ARM-64 (Native)
Role: Foreground
Parent Process: launchd [1]
Coalition: andy.DeadLineTodo [2089]
Date/Time: 2024-06-08 19:13:53.6259 +0800
Launch Time: 2024-06-08 19:13:53.2839 +0800
OS Version: iPhone OS 17.5.1 (21F90)
Release Type: User
Baseband Version: 2.60.02
Report Version: 104
Exception Type: EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x0000000195a2d8c0
Termination Reason: SIGNAL 5 Trace/BPT trap: 5
Terminating Process: exc handler [5556]
Triggered by Thread: 0
Thread 0 name:
Thread 0 Crashed:
0 libswiftCore.dylib 0x0000000195a2d8c0 _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:144)
1 DeadLineTodo 0x0000000100dde700 DeadLineTodoApp.init() + 1140 (DeadLineTodoApp.swift:46)
2 DeadLineTodo 0x0000000100ddef30 protocol witness for App.init() in conformance DeadLineTodoApp + 28 (<compiler-generated>:0)
3 SwiftUI 0x000000019b2c84c0 static App.main() + 116 (App.swift:114)
4 DeadLineTodo 0x0000000100ddeec4 static DeadLineTodoApp.$main() + 40 (<compiler-generated>:0)
5 DeadLineTodo 0x0000000100ddef5c main + 12 (DeadLineTodoApp.swift:32)
6 dyld 0x00000001ba7d1e4c start + 2240 (dyldMain.cpp:1298)
Thread 1:
0 libsystem_pthread.dylib 0x00000001f3fa40c4 start_wqthread + 0 (:-1)
Thread 2:
0 libsystem_pthread.dylib 0x00000001f3fa40c4 start_wqthread + 0 (:-1)
Thread 0 crashed with ARM Thread State (64-bit):
x0: 0x8000000100f01ad0 x1: 0x0000000000000000 x2: 0x0000000000000000 x3: 0x00000003019e9bc0
x4: 0x0000000000000000 x5: 0x000000016f16f3e0 x6: 0x000000000000002e x7: 0x0000000000000000
x8: 0x0000000000000100 x9: 0x00000000000000ff x10: 0x0000000000001b80 x11: 0x00000000f3444870
x12: 0x00000000000007fb x13: 0x00000000000007fd x14: 0x00000000f364506f x15: 0x000000000000006f
x16: 0x00000000f3444870 x17: 0x0000000000045000 x18: 0x0000000000000000 x19: 0x0000000100f01dba
x20: 0x8000000100f01ad0 x21: 0x0000000000000000 x22: 0x000000000000000b x23: 0x0000000000000022
x24: 0x000000000000002e x25: 0x0000000100f01ac0 x26: 0xd000000000000025 x27: 0x0000000000000000
x28: 0x0000000000000000 fp: 0x000000016f16f5c0 lr: 0x0000000195a2d8c0
sp: 0x000000016f16f4f0 pc: 0x0000000195a2d8c0 cpsr: 0x60001000
esr: 0xf2000001 (Breakpoint) brk 1
Binary Images:
0x100c90000 - 0x100f0ffff DeadLineTodo arm64 <c16650393d4537299a08b798b8227d31> /private/var/containers/Bundle/Application/348CC8D5-05FD-41DF-93A3-C15562EF4AA8/DeadLineTodo.app/DeadLineTodo
0x101214000 - 0x10121ffff libobjc-trampolines.dylib arm64e <2e2c05f8377a30899ad91926d284dd03> /private/preboot/Cryptexes/OS/usr/lib/libobjc-trampolines.dylib
0x1959f4000 - 0x195f43fff libswiftCore.dylib arm64e <d9ad5cc1ca2c3f0a8091652b0df56d14> /usr/lib/swift/libswiftCore.dylib
0x19af1c000 - 0x19ccbafff SwiftUI arm64e <c1325fda9da239d2ab83a338b4d8a884> /System/Library/Frameworks/SwiftUI.framework/SwiftUI
0x1ba795000 - 0x1ba821ef7 dyld arm64e <71846eacee653697bf7d790b6a07dcdb> /usr/lib/dyld
0x1f3fa3000 - 0x1f3fafff3 libsystem_pthread.dylib arm64e <1196b6c3333d3450818ff3663484b8eb> /usr/lib/system/libsystem_pthread.dylib
EOF
DeadLineTodoApp.swift
import SwiftData
typealias TodoData = TodoDataSchemaV8.TodoData
typealias UserSetting = TodoDataSchemaV8.UserSetting
enum TodoDataMigrationPlan: SchemaMigrationPlan {
static var schemas: [VersionedSchema.Type] {
[TodoDataSchemaV1.self, TodoDataSchemaV2.self, TodoDataSchemaV3.self, TodoDataSchemaV4.self, TodoDataSchemaV5.self, TodoDataSchemaV6.self, TodoDataSchemaV7.self, TodoDataSchemaV8.self]
}
static var stages: [MigrationStage]{
[migrationV1toV2, migrationV2toV3, migrationV3toV4, migrationV4toV5, migrationV5toV6, migrationV6toV7, migrationV7toV8]
}
static let migrationV1toV2 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV1.self, toVersion: TodoDataSchemaV2.self)
static let migrationV2toV3 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV2.self, toVersion: TodoDataSchemaV3.self)
static let migrationV3toV4 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV3.self, toVersion: TodoDataSchemaV4.self)
static let migrationV4toV5 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV4.self, toVersion: TodoDataSchemaV5.self)
static let migrationV5toV6 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV5.self, toVersion: TodoDataSchemaV6.self)
static let migrationV6toV7 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV6.self, toVersion: TodoDataSchemaV7.self)
static let migrationV7toV8 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV7.self, toVersion: TodoDataSchemaV8.self)
}
@main
struct DeadLineTodoApp: App {
let container: ModelContainer
@StateObject var store = StoreKitManager()
@State var updated: Bool = false
init() {
do {
container = try ModelContainer(
for: TodoData.self, UserSetting.self,
migrationPlan: TodoDataMigrationPlan.self)
} catch {
fatalError("Failed to initialize model container.")
}
}
var body: some Scene {
WindowGroup {
ContentView(updated: $updated)
.environmentObject(store)
}
.modelContainer(container)
}
}
Hello All, some background information first. I have the following struct:
Struct Category: Identifiable, Codeable, Hashable {
var id: UUID
var name: String
var subCategory: [Category]?
}
var categories: [Category]
There is no limit how many levels deep the subcategory can be. The user is essentially creating a hierarchical data filing system.
Given that the number of subCategory levels is unlimited, I am recursing over the subcategories to find the correct level at which to insert the newCategory.
The recursive function to add category is declared as:
func recursiveAddCategory(newCategory: Category, subCategoryOf: inout [Category]?)
you will note that I am trying to pass the subCategory as a reference (using inout), so that I can add to the original
and the function is called as recursiveAddCategory(newCategory, &categories.subCategory!)
the actual append statement within the recursiveAddCategory function is:
categories.subCategory?.append(newCategory)
I am encountering no errors but also find that the newCategory is not being added to the categories array.
Any help or guidance appreciated.
Thanks
I want to provide my own thumbnails for the file types which System already provides thumbnails for. I tried using QLThumbnailProvider however it works only when the file type is custom. For system supported file types it doesn't allow me to override my own thumbnails. Is there any alternative to this?
Hi everyone,
I am developing an application for macOS and need to monitor the network usage (bytes sent and received) of specific processes. Previously, I used the nettop command to achieve this, but I found that it leads to high CPU usage, often reaching 95%.
I'm looking for alternative methods to obtain the network usage information of processes. This could be through a different command or an available macOS API. Any suggestions or guidance on more efficient ways to gather this data would be greatly appreciated.
Thank you!
I'm experiencing a new error in SwiftData since updating to Xcode 16/iOS 17 DB1. When passing in a model (Student) to a view and then displaying an array of Points using ForEach, I get the following fatal error:
SwiftData/ModelCoders.swift:2438: Fatal error: Failed to locate relationship for StringCodingKey(stringValue: "group", intValue: nil) on Entity - name: Point
superentity:
subentities:
storedProperties:
CompositeAttribute - name: type, options: [], valueType: PointType, defaultValue: nil
Properties:
Attribute - name: type, options: [], valueType: String, defaultValue: nil, hashModifier: nil
Relationship - name: outcome, options: [], valueType: Outcome, destination: Outcome, inverseName: nil, inverseKeypath: nil
CompositeAttribute - name: proficiency, options: [], valueType: Proficiency, defaultValue: nil
Properties:
Attribute - name: proficiency, options: [], valueType: String, defaultValue: nil, hashModifier: nil
Attribute - name: date, options: [], valueType: Date, defaultValue: nil, hashModifier: nil
Attribute - name: note, options: [], valueType: String, defaultValue: nil, hashModifier: nil
Relationship - name: student, options: [], valueType: Optional<Student>, destination: Student, inverseName: points, inverseKeypath: Optional(\Student.points)
Attribute - name: group, options: [], valueType: Array<PersistentIdentifier>, defaultValue: [], hashModifier: nil
inheritedProperties:
uniquenessConstraints:
indices:
Xcode flags this line of the macro-generated getter of the outcome property on Point:
@storageRestrictions(accesses: _$backingData, initializes: _outcome)
init(initialValue) {
_$backingData.setValue(forKey: \.outcome, to: initialValue)
_outcome = _SwiftDataNoType()
}
get {
_$observationRegistrar.access(self, keyPath: \.outcome)
return self.getValue(forKey: \.outcome) // Fatal error: Failed to locate relationship for StringCodingKey...
}
set {
_$observationRegistrar.withMutation(of: self, keyPath: \.outcome) {
self.setValue(forKey: \.outcome, to: newValue)
}
}
This worked just fine in iOS 17. Here's a snippet of the Student implementation:
@Model
class Student: Identifiable, Comparable {
var name: String
var number: Int
@Relationship(deleteRule: .cascade, inverse: \Point.student) var points: [Point]
@Relationship(deleteRule: .cascade, inverse: \Mark.student) var marks: [Mark]
@Relationship(deleteRule: .nullify, inverse: \StudentGroup.students) var groups: [StudentGroup] = []
var archived: Bool
}
and the implementation of Point:
@Model
class Point: Identifiable, Comparable {
var student: Student?
var type: PointType
var outcome: Outcome
var proficiency: Proficiency
var group: [Student.ID] = []
var date: Date
var note: String
}
and finally the implementation for Outcome:
@Model
class Outcome: Identifiable, Comparable {
var name: String
var index: Int
var rubric: Rubric?
var proficiencies: [Proficiency]
}
I've tried adding a relationship in Outcome as an inverse of the outcomes property on Points (although this does not make sense in my implementation, which is why I initially did not set a relationship here) and the problem persisted.
Any ideas what this error means and how I might go about fixing it?
I'm trying to insert values into my SwiftData container but it crashes on insert context.insert(fhirObject) and the only error I get from Xcode is:
@Transient
private var _hkID: _SwiftDataNoType?
// original-source-range: /Users/cyril/Documents/GitHub/MyApp/MyApp/HealthKit/FHIR/FHIRModels.swift:35:20-35:20
configured as follows:
import SwiftData
import SwiftUI
@main
struct MyApp: App {
var container: ModelContainer
init() {
do {
let config = ModelConfiguration(cloudKitDatabase: .private("iCloud.com.author.MyApp"))
container = try ModelContainer(for: FHIRObservation.self, configurations: config)
UserData.shared = UserData(modelContainer: container)
} catch {
fatalError("Failed to configure SwiftData container.")
}
}
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(UserData.shared)
}
.modelContainer(container)
}
}
My UserData and DataStore are configured as follows:
import SwiftUI
import SwiftData
import os
/// `FHIRDataStore` is an actor responsible for updating the SwiftData db as needed on the background thread.
private actor FHIRDataStore {
let logger = Logger(
subsystem:
"com.author.MyApp.FHIRDataStore",
category: "ModelIO")
private let container: ModelContainer
init(container: ModelContainer) {
self.container = container
}
func update(newObservations: [FHIRObservationWrapper], deletedObservations: [UUID]) async throws {
let context = ModelContext(container)
// [FHIRObservationWrapper] -> [FHIRObservation]
// let modelUpdates = newObservations.lazy.map { sample in
// FHIRObservation(hkID: sample.hkID, fhirID: sample.fhirID, name: sample.name, status: sample.status, code: sample.code, value: sample.value, range: sample.range, lastUpdated: sample.lastUpdated)
// }
do {
try context.transaction {
for sample in newObservations {
let fhirObject = FHIRObservation(hkID: sample.hkID, fhirID: sample.fhirID, name: sample.name, status: sample.status, code: sample.code, value: sample.value, range: sample.range, lastUpdated: sample.lastUpdated)
// App crashes here
context.insert(fhirObject)
}
// for obj in modelUpdates {
//
// }
// try context.delete(model: FHIRObservation.self, where: #Predicate { sample in
// deletedObservations.contains(sample.hkID!)
// })
// try context.save()
logger.debug("Database updated successfully with new and deleted observations.")
}
} catch {
logger.debug("Catch me bro: \(error.localizedDescription)")
}
}
}
@MainActor
public class UserData: ObservableObject {
let userDataLogger = Logger(
subsystem:
"com.author.MyApp.UserData",
category: "Model")
public static var shared: UserData!
// MARK: - Properties
public lazy var healthKitManager = HKManager(withModel: self)
let modelContainer: ModelContainer
private var store: FHIRDataStore
init(modelContainer: ModelContainer) {
self.modelContainer = modelContainer
self.store = FHIRDataStore(container: modelContainer)
}
// MARK: - Methods
func updateObservations(newObservations: [FHIRObservationWrapper], deletedObservations: [UUID]) {
Task {
do {
try await store.update(newObservations: newObservations, deletedObservations: deletedObservations)
userDataLogger.debug("Observations updated successfully.")
} catch {
userDataLogger.error("Failed to update observations: \(error.localizedDescription)")
}
}
}
}
My @Model is configured as follows:
public struct FHIRObservationWrapper: Sendable {
let hkID: UUID
let fhirID: String
var name: String
var status: String
var code: FHIRCodeableConcept
var value: FHIRLabValueType
var range: FHIRLabRange?
var lastUpdated: Date?
}
@Model
public final class FHIRObservation {
let hkID: UUID?
let fhirID: String?
@Attribute(.allowsCloudEncryption) var name: String?
@Attribute(.allowsCloudEncryption) var status: String?
@Attribute(.allowsCloudEncryption) var code: FHIRCodeableConcept?
@Attribute(.allowsCloudEncryption) var value: FHIRLabValueType?
@Attribute(.allowsCloudEncryption) var range: FHIRLabRange?
@Attribute(.allowsCloudEncryption) var lastUpdated: Date?
init(hkID: UUID?, fhirID: String?, name: String? = nil, status: String? = nil, code: FHIRCodeableConcept? = nil, value: FHIRLabValueType? = nil, range: FHIRLabRange? = nil, lastUpdated: Date? = nil) {
self.hkID = hkID
self.fhirID = fhirID
self.name = name
self.status = status
self.code = code
self.value = value
self.range = range
self.lastUpdated = lastUpdated
}
}
Any help would be greatly appreciated!