Post

Replies

Boosts

Views

Activity

NavigationStack and NavigationSplitView Runtime warnings
Overview: When running the demo code presented in "The SwiftUI cookbook for navigation" (https://developer.apple.com/wwdc22/10054) I ran into some issues: Runtime warnings: 2022-06-08 22:20:31.587169+0800 NavigationSplitViewDemo[17797:672165] [SwiftUI] A NavigationLink is presenting a value of type “Category” but there is no matching navigation destination visible from the location of the link. The link cannot be activated. onChange(of: UpdateTrigger) action tried to update multiple times per frame. 2022-06-08 22:15:23.432289+0800 NavigationSplitViewDemo[17645:662571] [UIFocus] _TtGC7SwiftUI14_UIHostingViewGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__ implements focusItemsInRect: - caching for linear focus movement is limited as long as this view is on screen. Feedback filed: FB10103041 and FB10104196
13
4
8.2k
Aug ’22
SwiftData Query relationships not working
Overview I have 2 models: Deparment and Student Each Department can contain multiple students Each Student can only be in one Department I have DepartmentList, tapping on the department should take it to the StudentList which lists all students in the department Problem When I use Query in StudentList to filter only students for a specific department id, no students are shown. Questions: What should I do to list the students in a department? (see complete code below). let filter = #Predicate<Student> { student in student.department?.id == departmentID } let query = Query(filter: filter, sort: \.name) _students = query Complete code App @main struct SchoolApp: App { var body: some Scene { WindowGroup { ContentView() } .modelContainer(for: [Department.self, Student.self]) } } Department import Foundation import SwiftData @Model class Department { var id: UUID var name: String var students: [Student] init( id: UUID, name: String, students: [Student] = [] ) { self.id = id self.name = name self.students = students } } Student import Foundation import SwiftData @Model class Student { var id: UUID var name: String @Relationship(inverse: \Department.students) var department: Department? init( id: UUID, name: String, department: Department? = nil ) { self.id = id self.name = name self.department = department } } ContentView import SwiftUI struct ContentView: View { @State private var selectedDepartment: Department? var body: some View { NavigationSplitView { DepartmentList(selectedDepartment: $selectedDepartment) } detail: { if let department = selectedDepartment { StudentList(department: department) } else { Text("no department selected") } } .task { printStoreFilePath() } } private func printStoreFilePath() { let urls = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask) if let path = urls.map({ $0.path(percentEncoded: false) }).first { print("Storage: \(path)") } } } DepartmentList import SwiftUI import SwiftData struct DepartmentList: View { @Binding var selectedDepartment: Department? @Query(sort: \.name) private var departments: [Department] @Environment(\.modelContext) private var modelContext var body: some View { List(selection: $selectedDepartment) { ForEach(departments) { department in NavigationLink(value: department) { Text(department.name) } } } .toolbar { ToolbarItem { Button { addDepartment() } label: { Label("Add", systemImage: "plus") } } } } private func addDepartment() { guard let index = (1000..<10000).randomElement() else { return } let department = Department(id: UUID(), name: "Department \(index)") modelContext.insert(department) } } StudentList import SwiftUI import SwiftData struct StudentList: View { var department: Department @Query private var students: [Student] @Environment(\.modelContext) private var modelContext init(department: Department) { self.department = department let departmentID = department.id let filter = #Predicate<Student> { student in student.department?.id == departmentID } let query = Query(filter: filter, sort: \.name) _students = query } var body: some View { List { ForEach(students) { student in Text(student.name) } } .toolbar { ToolbarItem { Button { addStudent() } label: { Label("Add", systemImage: "plus") } } } } private func addStudent() { guard let index = (1000..<10000).randomElement() else { return } let student = Student( id: UUID(), name: "Student \(index)", department: department ) modelContext.insert(student) } }
10
4
4.0k
Jul ’23
Logger on Xcode console
Overview: I am logging some messages using Logger I would like these messages to be printed on to Xcode without the timestamp and other details I want only the message to be displayed Questions: How can I display only the message on the Xcode console (see preferred output)? Is there a setting in Xcode to remove the timestamp prefix? Is there an alternate approach? Note: I need to use Logger because this app would be released, so print is not an option. Example Code import SwiftUI import os struct ContentView: View { let logger = Logger(subsystem: "MyApp", category: "MyCategory") var body: some View { Text("Hello, world!") .onAppear { logger.debug("content view displayed") } } } Actual Output: 2022-11-25 18:41:10.116408+0800 Demo[36175:5518724] [MyCategory] content view displayed Preferred Output: One of the following would be ideal: content view displayed Demo[36175:5518724] [MyCategory] content view displayed My Failed Attempt I event tried to use print in debug mode, but couldn't make it compile: Following is my failed attempt: import os #if DEBUG struct Logger { let subsystem: String let category: String func debug(_ message: String) { print(message) } //This will not help: // func debug(_ message: OSLogMessage) { // print(message) // } } #endif
4
1
4.6k
Nov ’22
Toolbar Menu button seems to look disabled
Overview On macOS, in a NavigationSplitView when the menu button is added to the detail view toolbar, it seems to look disabled Environment Xcode: 14.1 beta 3 (14B5033e) macOS: 13.0 Beta (22A5365d) Code: struct ContentView: View { @State private var selectedNumber: Int? var body: some View { NavigationSplitView { List(0..<100, selection: $selectedNumber) { number in Text("cell \(number)") } } detail: { Text("Detail") .toolbar { ToolbarItem { Menu { Button("aa") {} Button("bb") {} } label: { Label("Add Bookmark", systemImage: "book") } } } } } } Steps to reproduce: Run the project on macOS Select cell 0 on the sidebar Click on the book toolbar button and notice the menu appear Select cell 1 on the sidebar Expected Behaviour After step 4, the book toolbar button should look prominent (like it is enabled) Actual Behaviour After step 4, the book toolbar button looks like it is disabled. Screenshot
1
1
1.6k
Nov ’23
FB11794798: NSPersistentCloudKitContainer throws lots of error / debug messages
Hi, When using NSPersistentCloudKitContainer lots of error / debug messages are shown in Xcode Debug area. Feedback FB11794798: Overview When I use NSPersistentCloudKitContainer I get the following error / debug messages printed on the Xcode Debug Area. Syncing seems to happen fine. Tested on device and simulator. I am still using Development (not deployed to Production yet) I even tried with a new project using the default code generated for by enabling CloudKit coredata sync and I still get the same messages. I have filed a feedback FB11794798 Steps to Reproduce Create a new project check Use CoreData and Host in CloudKit check boxes Run the project Notice the error messages shown below. Questions How to resolve these errors? Or is this a bug from the Apple Frameworks? (Feedback FB11794798) Error / debug message printed on Xcode debug area CoreData: debug: CoreData+CloudKit: -[PFCloudKitOptionsValidator validateOptions:andStoreOptions:error:](36): Validating options: <NSCloudKitMirroringDelegateOptions: 0x600000760510> containerIdentifier:<MyContainerID> databaseScope:Private ckAssetThresholdBytes:<null> operationMemoryThresholdBytes:<null> useEncryptedStorage:NO useDeviceToDeviceEncryption:NO automaticallyDownloadFileBackedFutures:NO automaticallyScheduleImportAndExportOperations:YES skipCloudKitSetup:NO preserveLegacyRecordMetadataBehavior:NO useDaemon:YES apsConnectionMachServiceName:<null> containerProvider:<PFCloudKitContainerProvider: 0x600003764210> storeMonitorProvider:<PFCloudKitStoreMonitorProvider: 0x600003764220> metricsClient:<PFCloudKitMetricsClient: 0x600003764230> metadataPurger:<PFCloudKitMetadataPurger: 0x600003764240> scheduler:<null> notificationListener:<null> containerOptions:<null> defaultOperationConfiguration:<null> progressProvider:<NSPersistentCloudKitContainer: 0x60000205d200> test_useLegacySavePolicy:YES archivingUtilities:<PFCloudKitArchivingUtilities: 0x600003764250> bypassSchedulerActivityForInitialImport:NO storeOptions: { NSInferMappingModelAutomaticallyOption = 1; NSMigratePersistentStoresAutomaticallyOption = 1; NSPersistentCloudKitContainerOptionsKey = "<NSPersistentCloudKitContainerOptions: 0x600003b3a190>"; NSPersistentHistoryTrackingKey = 1; NSPersistentStoreMirroringOptionsKey = { NSPersistentStoreMirroringDelegateOptionKey = "<NSCloudKitMirroringDelegate: 0x600000c642a0>"; }; NSPersistentStoreRemoteChangeNotificationOptionKey = 1; } CoreData: debug: CoreData+CloudKit: -[NSCloudKitMirroringDelegate observeChangesForStore:inPersistentStoreCoordinator:](416): <NSCloudKitMirroringDelegate: 0x600000c642a0>: Observing store: <NSSQLCore: 0x14080aec0> (URL: file:///Users/<my home folder>/Library/Group%20Containers/group.<app name>/<filename>.sqlite) CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _setUpCloudKitIntegration](562): <NSCloudKitMirroringDelegate: 0x600000c642a0>: Successfully enqueued setup request. CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate checkAndExecuteNextRequest](3209): <NSCloudKitMirroringDelegate: 0x600000c642a0>: Checking for pending requests. CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate checkAndExecuteNextRequest]_block_invoke(3222): <NSCloudKitMirroringDelegate: 0x600000c642a0>: Executing: <NSCloudKitMirroringDelegateSetupRequest: 0x600001643f20> D3975DD0-1198-40F2-9D6A-B9994B9710B6 CoreData: debug: CoreData+CloudKit: -[PFCloudKitMetadataModelMigrator calculateMigrationStepsWithConnection:error:](446): Skipping migration for 'ANSCKDATABASEMETADATA' because it already has a column named 'ZLASTFETCHDATE'
0
1
1.4k
Nov ’22
List Section with Swipe Action - glitches
Overview I have an iOS project where I have a list with sections. Each cell in the section can be swiped to have some action What needs to be done When swipe button is pressed the cell needs to move from one section to the other without a UI glitch. Problem When I press the swipe action button, there is a UI glitch and some warnings are thrown. UICollectionView internal inconsistency: unexpected removal of the current swipe occurrence's mask view. Please file a bug against UICollectionView. Reusable view: <SwiftUI.ListCollectionViewCell: 0x10700c200; baseClass = UICollectionViewListCell; frame = (16 40.3333; 370 52); hidden = YES; layer = <CALayer: 0x600000c12fa0>>; Collection view: <SwiftUI.UpdateCoalescingCollectionView: 0x106820800; baseClass = UICollectionView; frame = (0 0; 402 874); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x600000c13330>; backgroundColor = <UIDynamicSystemColor: 0x60000173a9c0; name = systemGroupedBackgroundColor>; layer = <CALayer: 0x600000c3a070>; contentOffset: {0, -62}; contentSize: {402, 229}; adjustedContentInset: {62, 0, 34, 0}; layout: <UICollectionViewCompositionalLayout: 0x10590edb0>; dataSource: <_TtGC7SwiftUI31UICollectionViewListCoordinatorGVS_28CollectionViewListDataSourceOs5Never_GOS_19SelectionManagerBoxS2___: 0x106822a00>>; Swipe occurrence: <UISwipeOccurrence: 0x103c161f0; indexPath: <NSIndexPath: 0xab1f048608f3828b> {length = 2, path = 0 - 0}, state: .triggered, direction: left, offset: 0> Test environment: Xcode 26.0.1 (17A400) iOS 26 Simulator (iPhone 17 Pro) Feedback filed: FB20890361 Code I have pasted below the minimum reproducible code ContentView import SwiftUI struct ContentView: View { @State private var dataStore = DataStore() var body: some View { List { ToDoSection(status: .notStarted, toDos: notStartedToDos) ToDoSection(status: .inProgress, toDos: inProgressToDos) ToDoSection(status: .completed, toDos: completedTodos) } } var notStartedToDos: [Binding<ToDoItem>] { $dataStore.todos.filter { $0.wrappedValue.status == .notStarted } } var inProgressToDos: [Binding<ToDoItem>] { $dataStore.todos.filter { $0.wrappedValue.status == .inProgress } } var completedTodos: [Binding<ToDoItem>] { $dataStore.todos.filter { $0.wrappedValue.status == .completed } } } ToDoSection import SwiftUI struct ToDoSection: View { let status: ToDoItem.Status let toDos: [Binding<ToDoItem>] var body: some View { if !toDos.isEmpty { Section(status.title) { ForEach(toDos) { toDo in Text(toDo.wrappedValue.title) .swipeActions(edge: .trailing) { if status == .notStarted { Button("Start") { toDo.wrappedValue.status = .inProgress } } if status != .completed { Button("Complete") { toDo.wrappedValue.status = .completed } Button("Move back") { toDo.wrappedValue.status = .notStarted } } } } } } } } ToDoItem import Foundation struct ToDoItem: Identifiable { let id: UUID let title: String var status: Status } extension ToDoItem { enum Status: Equatable { case notStarted case inProgress case completed var title: String { switch self { case .notStarted: "Not Started" case .inProgress: "In Progress" case .completed: "Completed" } } } } DataStore import Foundation @Observable class DataStore { var todos: [ToDoItem] init() { todos = [ ToDoItem(id: UUID(), title: "aaa", status: .notStarted), ToDoItem(id: UUID(), title: "bbb", status: .notStarted), ToDoItem(id: UUID(), title: "ccc", status: .notStarted) ] } }
Topic: UI Frameworks SubTopic: SwiftUI
4
1
218
Nov ’25
Binding value from an ObservableObject
Aim:I have a model which is an ObservableObject. It has a Bool property, I would like to use this Bool property to initialise a @Binding variable.Questions:How to convert an @ObservableObject to a @Binding ?Is creating a @State the only way to initialise a @Binding ?Note:I do understand I can make use of @ObservedObject / @EnvironmentObject, and I see it's usefulness, but I am not sure a simple button needs to have access to the entire model.Or is my understanding incorrect ?Code:import SwiftUI import Combine import SwiftUI import PlaygroundSupport class Car : ObservableObject { @Published var isReadyForSale = true } struct SaleButton : View { @Binding var isOn : Bool var body: some View { Button(action: { self.isOn.toggle() }) { Text(isOn ? "On" : "Off") } } } let car = Car() //How to convert an ObservableObject to a Binding //Is creating an ObservedObject or EnvironmentObject the only way to handle a Observable Object ? let button = SaleButton(isOn: car.isReadyForSale) //Throws a compilation error and rightly so, but how to pass it as a Binding variable ? PlaygroundPage.current.setLiveView(button)
3
5
24k
Sep ’21
Xcode Cloud error: Swift Package dependency for app extension
Overview I have a swift package that I have added to the app target. On the app extension (widget) target I have added the same package under Frameworks and Libraries. I am able to archive successfully when I do it manually When I start a build using Xcode Cloud I get the following errors: Error: An internal error was detected which caused this stage to error. The error has been logged, and you can re-run this build again. Resolve package dependencies Command exited with non-zero exit-code: 74 fatal: could not read Username for 'http://github.com': terminal prompts disabledan out-of-date resolved file was detected at /Volumes/workspace/repository/<app name>.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved, which is not allowed when automatic dependency resolution is disabled; please make sure to update the file to reflect the changes in dependencies. Running resolver because the following dependencies were added: '<package name>' (https://github.com/<user name>/<package name>.git)2022-11-11 01:21:37.643 xcodebuild[2273:9107] Writing error result bundle to /var/folders/hf/lmqg8qtx531_sq5gwgt5s3ch0000gn/T/ResultBundle_2022-11-11_01-21-0037.xcresult Make sure that Package.resolved is up to date on the '<branch name>' branch, and that this branch has been pushed to your remote repository. Save artifacts Upload <app name> Build 16 Logs for <app name> archive An internal error occurred while this artifact was being saved. Questions: Am I missing something? How do I resolve this issue? Is it because of a server issue?
1
1
2.8k
Nov ’22
Add keyboard shortcut for Search
Overview I have a SwiftUI list with a search field I would like to add a keyboard shortcut for search field to be in focus Questions: How can I add a keyboard shortcut for search field? import SwiftUI struct ContentView: View { @State private var searchText = "" var body: some View { NavigationStack { List(0..<100) { index in Text("Cell \(index)") } .searchable(text: $searchText) } } }
0
1
901
Dec ’22
How to download macOS Sonoma installer?
I am only able to upgrade from Ventura to Sonoma. I don't want to upgrade, I would like to download the installer so that I can install Sonoma on a separate Volume instead of upgrading. Am I missing something? I only see an option to upgrade and the developer website only allows me to download a IPSW file. I have only 1 Mac and I am not sure how I can use the IPSW file to install macOS Sonoma. Any help would be much appreciated, thanks
18
1
18k
Oct ’23
Copyable doesn't work with NavigationSplitView
Problem When copyable is used with NavigationSplitView then it doesn't work The menu Edit > Copy is disabled Note When copyable is not used with a NavigationSplitView and used only with a plain List then it works. Question Is there anything I am missing? Feedback FB12990593 Platform macOS 14.0 Beta (23A5312d) Xcode 15.0 beta 6 (15A5219j) Steps to reproduce Run the app on mac Select some cars Press Command C Expected Behaviour Menu Edit > Copy should be enabled Pressing Command C should allow user to copy selected cars Actual Behaviour Menu Edit > Copy is disabled Pressing Command C doesn't allow user to copy selected cars Code struct ContentView: View { @State private var dataStore = DataStore() var body: some View { NavigationSplitView { Color.brown } detail: { CarListView(dataStore: dataStore) } } } struct CarListView: View { let dataStore: DataStore @State private var selectedCarIDs = Set<UUID>() var body: some View { List(selection: $selectedCarIDs) { ForEach(dataStore.cars) { car in CarCell(car: car) .draggable(car) } } .copyable(selectedCars()) } private func selectedCars() -> [Car] { dataStore.cars.filter { selectedCarIDs.contains($0.id) } } } struct CarCell: View { let car: Car var body: some View { VStack(alignment: .leading) { Text(car.name) Text("\(car.price)") } } } @Observable class DataStore { var cars = [ Car(name: "aaa", price: 10), Car(name: "bbb", price: 20), Car(name: "ccc", price: 30), Car(name: "ddd", price: 40) ] } struct Car: Codable, Transferable, Identifiable { let id: UUID let name: String let price: Int init(name: String, price: Int) { self.id = UUID() self.name = name self.price = price } static var transferRepresentation: some TransferRepresentation { CodableRepresentation(contentType: .car) } } extension UTType { static let car = UTType("com.example.car")! }
2
2
900
Aug ’23
#Predicate doesn't work with enum
Problem The following code doesn't work: let predicate = #Predicate<Car> { car in car.size == size //This doesn't work } Console Error Query encountered an error: SwiftData.SwiftDataError(_error: SwiftData.SwiftDataError._Error.unsupportedPredicate) Root cause Size is an enum, #Predicate works with other type such as String however doesn't work with enum Enum value is saved however is not filtered by #Predicate Environment Xcode: 15.0 (15A240d) - App Store macOS: 14.0 (23A339) - Release Candidate Steps to reproduce Run the app on iOS 17 or macOS Sonoma Press the Add button Notice that the list remains empty Expected behaviour List should show the newly created small car Actual behaviour List remains empty inspite of successfully creating the small car. Feedback FB13194334 Code Size enum Size: String, Codable { case small case medium case large } Car import SwiftData @Model class Car { let id: UUID let name: String let size: Size init( id: UUID, name: String, size: Size ) { self.id = id self.name = name self.size = size } } ContentView struct ContentView: View { var body: some View { NavigationStack { CarList(size: .small) } } CarList import SwiftUI import SwiftData struct CarList: View { let size: Size @Environment(\.modelContext) private var modelContext @Query private var cars: [Car] init(size: Size) { self.size = size let predicate = #Predicate<Car> { car in car.size == size //This doesn't work } _cars = Query(filter: predicate, sort: \.name) } var body: some View { List(cars) { car in VStack(alignment: .leading) { Text(car.name) Text("\(car.size.rawValue)") Text(car.id.uuidString) .font(.footnote) } } .toolbar { Button("Add") { createCar() } } } private func createCar() { let name = "aaa" let car = Car( id: UUID(), name: name, size: size ) modelContext.insert(car) } }
6
1
2.4k
May ’25
Extract Data from P8 file
Hi,I am trying to extract the data from the P8 file to use it generate JWT.I understand that it is possible using dumpasn1 and extracting the OCTET STRING section. This is great, and is definitely possible.I was wondering if it was possible to do it on macOS using Apple's APIs (example SecItemImport), would make it simpler if it was possible all in the mac app.I tried the following but it didn't work:Error: I got the OSStatus as -25257Questions:- Is there a way to do this using SecItemImport or any other Apple APIs as I am using it in a command line mac app ?- Are the parameters to SecItemImport are incorrect ?- Am down the wrong path? , any direction to the correct API would help.What I tried with SecItemImport:- Data extracted from the file- Decoding the data from the file- Some input formatsMany thanks.import Foundation import Security func f1() { do { let fileURL = URL(fileURLWithPath: "some valid path"); let data = try Data(contentsOf: fileURL) guard let string = String(data: data, encoding: .utf8) else { print("Failed to convert data to string") return } let b64Text = string .replacingOccurrences(of: "-----END PRIVATE KEY-----", with: "") .replacingOccurrences(of: "-----BEGIN PRIVATE KEY-----", with: "") .replacingOccurrences(of: "\n", with: "") guard let b64Data = b64Text.data(using: .utf8), let decodedData = Data(base64Encoded: b64Data) else { print("Was not b64 data") return } print(string) var outArray : CFArray? let filename : CFString? = nil var inputFormat = SecExternalFormat.formatUnknown var itemType = SecExternalItemType.itemTypePrivateKey let flags = SecItemImportExportFlags() //I tried data, b64Data, decodedData all seems to return an error let status = SecItemImport(decodedData as CFData, filename, &amp;inputFormat, &amp;itemType, flags, nil, nil, &amp;outArray) //status = -25257 print("status = \(status)") for element in (outArray as [AnyObject]?) ?? [] { print("element = \(element)") } } catch { print("Error: \(error)") } } f1()
4
0
5.9k
May ’21
Lab appointment - Pending status
Hi, My lab appointment status is pending. The lab is for tomorrow. When would I get to know if my lab appointment has been accepted. It is my first time for a lab appointment, also I forgot to mention the feedback IDs, would there be a way to amend the request to include the feedback IDs if that would help. (Feedback assistant was down when I booked an appointment so couldn't get the feedback IDs.) Any help would be much appreciated as I am from a different timezone and would need to plan accordingly .... really praying I get an appointment
1
0
1.1k
Jun ’22
How to make Xcode Cloud compile code compiled in Xcode beta ?
Hi, I have an Xcode project that uses Xcode 14.0 beta 6 (14A5294g). How to make Xcode Cloud compile code compiled in Xcode beta? My code uses beta APIs that doesn't seem to compile on Xcode Cloud (throws compilation errors) Am I missing something as this would be a common scenario for many developers? How do I make the beta APIs compile on Xcode Cloud?
4
0
1.7k
Nov ’22