I want to expose few elements for accessibility alone and other for automation alone. But I can only accessibility elements in Accessibility Inspector but can't see Automation Elements
self.view.accessibilityElements = [loginButton as Any,
registerButton as Any,
closeButton as Any]
self.view.automationElements = [claimLabel as Any,
loginButton as Any,
registerButton as Any,
intoductionImage as Any,
closeButton as Any])
Swift
RSS for tagSwift is a powerful and intuitive programming language for Apple platforms and beyond.
Posts under Swift tag
200 Posts
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I'm still discovering swift and the various frameworks. So I'm now trying to create scrolling composition with a grid - containing images - and an NSStackView at on top.
However, I'm running into a problem that might seem stupid, but when I try to wrap my NSCollectionView in another NSView and pointing the scrollView.documentView to, I can't scroll anymore... Even though it works fine when I set the scrollView.documentView to the NSCollectionView directly.
Working case:
override func viewDidLoad() {
super.viewDidLoad()
scrollView = NSScrollView(frame: .zero)
scrollView.hasVerticalScroller = true
scrollView.hasHorizontalScroller = false
scrollView.scrollerStyle = .overlay
scrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scrollView)
vStack = NSStackView(frame: .zero)
vStack.orientation = .vertical
vStack.spacing = 12 * 2
vStack.translatesAutoresizingMaskIntoConstraints = false
let hStack = NSStackView()
hStack.orientation = .horizontal
hStack.spacing = 12
hStack.translatesAutoresizingMaskIntoConstraints = false
let label1 = NSTextField(labelWithString: "Collection")
hStack.addArrangedSubview(label1)
let layout = PinterestLayout()
layout.delegate = self
collectionView = NSCollectionView(frame: .zero)
collectionView.collectionViewLayout = layout
collectionView.dataSource = self
collectionView.delegate = self
collectionView
.register(
ArtCardCell.self,
forItemWithIdentifier: NSUserInterfaceItemIdentifier("ArtCardCell")
)
collectionView.backgroundColors = [.BG]
collectionView.translatesAutoresizingMaskIntoConstraints = false
// vStack.addArrangedSubview(hStack)
// vStack.addArrangedSubview(collectionView)
scrollView.documentView = collectionView
NSLayoutConstraint.activate([
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
scrollView.topAnchor.constraint(equalTo: view.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
// vStack.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
// vStack.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
// vStack.topAnchor.constraint(equalTo: scrollView.topAnchor),
// vStack.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
// vStack.widthAnchor.constraint(equalTo: scrollView.widthAnchor),
collectionView.widthAnchor.constraint(equalTo: scrollView.widthAnchor),
// vStack.arrangedSubviews[0].leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 12),
// vStack.arrangedSubviews[0].trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -12),
// vStack.arrangedSubviews[0].topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 80)
])
collectionView.postsBoundsChangedNotifications = true
NotificationCenter.default.addObserver(self, selector: #selector(didScroll(_:)),
name: NSView.boundsDidChangeNotification,
object: collectionView.enclosingScrollView?.contentView
)
}
collectionView height: 3549.0
ScrollView height: 628.0
StackView height: --
Dysfunctional case:
override func viewDidLoad() {
super.viewDidLoad()
scrollView = NSScrollView(frame: .zero)
scrollView.hasVerticalScroller = true
scrollView.hasHorizontalScroller = false
scrollView.scrollerStyle = .overlay
scrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scrollView)
vStack = NSStackView(frame: .zero)
vStack.orientation = .vertical
vStack.spacing = 12 * 2
vStack.translatesAutoresizingMaskIntoConstraints = false
let hStack = NSStackView()
hStack.orientation = .horizontal
hStack.spacing = 12
hStack.translatesAutoresizingMaskIntoConstraints = false
let label1 = NSTextField(labelWithString: "Collection")
hStack.addArrangedSubview(label1)
let layout = PinterestLayout()
layout.delegate = self
collectionView = NSCollectionView(frame: .zero)
collectionView.collectionViewLayout = layout
collectionView.dataSource = self
collectionView.delegate = self
collectionView
.register(
ArtCardCell.self,
forItemWithIdentifier: NSUserInterfaceItemIdentifier("ArtCardCell")
)
collectionView.backgroundColors = [.BG]
collectionView.translatesAutoresizingMaskIntoConstraints = false
vStack.addArrangedSubview(hStack)
vStack.addArrangedSubview(collectionView)
scrollView.documentView = vStack
NSLayoutConstraint.activate([
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
scrollView.topAnchor.constraint(equalTo: view.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
vStack.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
vStack.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
vStack.topAnchor.constraint(equalTo: scrollView.topAnchor),
vStack.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
vStack.widthAnchor.constraint(equalTo: scrollView.widthAnchor),
collectionView.widthAnchor.constraint(equalTo: scrollView.widthAnchor),
vStack.arrangedSubviews[0].leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 12),
vStack.arrangedSubviews[0].trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -12),
vStack.arrangedSubviews[0].topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 80)
])
}
collectionView height: 508.0
ScrollView height: 628.0
StackView height: 628.0
Hello there!
We have an app that connects to an external device via Wi-Fi to send and query content from it. This external device generates a hidden AP that the phone connects against. However, sometimes the app fails to connect to the external device with the system alert "Unable to join the network...".
We have been debugging for a couple but couldn't find any clear reason of why this thing is happening. What could be the reason behind this alert appearing?
For the connection, we are using the NEHotspotConfigurationManager to connect to the AP of this external device.
The configuration for the connection is the following:
NEHotspotConfiguration(
ssid: ssid,
passphrase: password,
isWEP: false
)
configuration.hidden = true
There are some logs that we extracted that show two connections.
One happened at 20:37, which was a successful connection.
wifi_logs_success 2.log
Another connection was made at 20:38, which failed.
wifi_logs_failure.log
Inspecting the logs, one difference that I see between them is the __WiFiDeviceManagerDispatchUserForcedAssociationCallback: result %lld, which in the successful case is 0 and in the failed case is 1.
Can anyone help with this? We're very lost on why this configuration could be an issue at all.
I have a stackview which have 2 labels
class TextView: UIView {
@IBOutlet private weak var stackView: UIStackView! {
didSet {
stackView.isAccessibilityElement = true
stackView.accessibilityLabel = label1.text + label2.text
}
}
@IBOutlet private weak var label1: UILabel! {
didSet {
label1.accessibilityIdentifier = "label1"
}
}
@IBOutlet private weak var: UILabel!{
didSet {
label2.accessibilityIdentifier = "label2"
}
}
}
My goal here is to have a combines accessibility label for the stackview and yet able to access the accessibilityIdentifier of child elements for automation.
Hello!
Is it possible to disable animation which appeared in iOS 18 when switching tab items?
I only found a solution for UIKit: https://forums.developer.apple.com/forums/thread/763122.
I am making a swift app supporting multi language ,showing proper language ui according user's phone setting language, I want to launch different screen (showing different image, boot-en.jpg, boot-ja.jpg) according language,i created two LaunchScreen files ,LaunchScreen-en.storyboard and LaunchScreen-ja.storyboard and localize them ,and add a different UIImage to them,
then create two InfoPlist.strings file with congfiging
."UILaunchStoryboardName" = "LaunchScreen_en"; //
"UILaunchStoryboardName" = "LaunchScreen_ja";//
and then **config info.plist ** with
UILaunchStoryboardName
LaunchScreen
above all steps ,build and run,hope to see launch screen showing boot-ja.jpg when phone's language is Japanese, showing boot-en.jpg when phone's language is English, but it shows black screen, how to fix this problem, thank you.
I would like to show a nswindow at a position on screen base on height of the nswindow and its content view. I received zero width and height on macOS 15.0 and xCode 16.1 however they were returned correct width and height on previous macOS version.
import Cocoa
import SwiftUI
class AppDelegate: NSObject, NSApplicationDelegate {
private var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
window = NSWindow(
contentRect: .zero,
styleMask: [.miniaturizable, .closable, .resizable],
backing: .buffered, defer: false)
window.title = "No Storyboard Window"
window.contentView = NSHostingView(rootView: ContentView()) // a swiftui view
window.center()
let windowFrame = window.frame
print("window Frame \(windowFrame)") // print width and height zero here
window.makeKeyAndOrderFront(nil)
}
}
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
}
.padding()
}
}
I tried window.layoutIfNeeded() after setting contentview but it didn't work
How can I get the frame after setting contentview for nswindow on macOS 15.0?
Hello,
I have a problem reading a 2D data matrix type code with a camera. In the application, I use AVFoundation to operate the camera and work with 2D codes, and in the vast majority there is no problem with loading. Nothing special.
I originally thought it might be a problem in my code, but I got the same result when I tried with the Camera app integrated in IOS. It can be seen that only the LiveText API for text recognition worked.
But I am attaching the code with which the camera has a problem, even though the code looks perfectly fine at first glance. A classic handheld 2D code reader will read the code just fine.
Can someone please explain to me why the camera, which normally reads these codes at the speed of light, sometimes has a problem with the codes?
Thank you
[Personal Information Edited by Moderator]
"Hi everyone! We've encountered an issue with uploading our app to the App Store. We received the Family Controls Distribution permission, updated the certificates and profiles, submitted it for review, but received feedback that the request simply doesn't appear for the moderators. Does anyone know what the problem might be? Our request is: try await center.requestAuthorization(for: .individual). We also confirmed that the device must have TouchID or FaceID installed."
Topic:
App Store Distribution & Marketing
SubTopic:
App Review
Tags:
Swift
App Review
Family Controls
Screen Time
Hello All,
I'm developing a machine learning model for image classification, which requires managing an exceptionally large dataset comprising over 18,000 classes. I've encountered several hurdles while using Create ML, and I would appreciate any insights or advice from those who have faced similar challenges.
Current Issues:
Create ML Failures with Large Datasets:
When using Create ML, the process often fails with errors such as "Failed to create CVPixelBufferPool." This issue appears when handling particularly large volumes of data.
Custom Implementation Struggles:
To bypass some of the limitations of Create ML, I've developed a custom solution leveraging the MLImageClassifier within the CreateML framework in my own SwiftUI MacOS app.
Initially I had similar errors as I did in Create ML, but I discovered I could move beyond the "extracting features" stage without crashing by employing a workaround: using a timer to cancel and restart the job every 30 seconds. This method is the only way I've been able to finish the extraction phase, even with large datasets, but it causes many errors in the console if I allow it to run too long.
Lack of Progress Reporting:
Using MLJob<MLImageClassifier>, I've noticed that progress reporting stalls after the feature extraction phase. Although system resources indicate activity, there is no programmatic feedback on what is occurring.
Things I've Tried:
Data Validation: Ensured that all images in the dataset are valid and non-corrupted, which helps prevent unnecessary issues from faulty data.
Custom Implementation with CreateML Framework: Developed a custom solution using the MLImageClassifier within the CreateML framework to gain more control over the training process.
Timer-Based Workaround: Employed a workaround using a timer to cancel and restart the job every 30 seconds to move past the "extracting features" phase, allowing progress even with larger datasets.
Monitoring System Resources: Observed ongoing system resource usage when process feedback stalled, confirming background processing activity despite the lack of progress reporting.
Subset Testing: Successfully created and tested a model on a subset of the data, which validated the approach worked for smaller datasets and could produce a functioning model.
Router Model Concept: Considered training multiple models for different subsets of data and implementing a "router" model to decide which specialized model to utilize based on input characteristics.
What I Need Help With:
Handling Large Datasets:
I'm seeking strategies or best practices for effectively utilizing Create ML with large datasets.
Any guidance on memory management or alternative methodologies would be immensely helpful.
Improving Progress Reporting:
I'm looking for ways to obtain more consistent and programmatic progress updates during the training and testing phases.
I'm working on a Mac M1 Pro w/ 32GB RAM, with Apple Silicon and am fully integrated within the Apple ecosystem. I am very grateful for any advice or experiences you could share to help overcome these challenges.
Thank you!
I've pasted the relevant code below:
func go() {
if self.trainingSession == nil {
self.trainingSession = createTrainingSession()
}
if self.startTime == nil {
self.startTime = Date()
}
job = try! MLImageClassifier.resume(self.trainingSession)
job.phase
.receive(on: RunLoop.main)
.sink { phase in
self.phase = phase
}
.store(in: &cancellables)
job.checkpoints
.receive(on: RunLoop.main)
.sink { checkpoint in
self.state = "\(checkpoint)\n\(self.job.progress)"
self.progress = self.job.progress.fractionCompleted + 0.2
self.updateTimeEstimates()
}
.store(in: &cancellables)
job.result
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
print("Training Failed: \(error.localizedDescription)")
case .finished:
print("🎉🎉🎉🎉 TRAINING SESSION FINISHED!!!!")
self.trainingFinished = true
}
}, receiveValue: { classifier in
Task {
await self.saveModel(classifier)
}
})
.store(in: &cancellables)
}
private func createTrainingSession() -> MLTrainingSession<MLImageClassifier> {
do {
print("Initializing training Data...")
let trainingData: MLImageClassifier.DataSource = .labeledDirectories(at: trainingDataURL)
let modelParameters = MLImageClassifier.ModelParameters(
validation: .split(strategy: .automatic),
augmentation: self.augmentations,
algorithm: .transferLearning(
featureExtractor: .scenePrint(revision: 2),
classifier: .logisticRegressor
)
)
let sessionParameters = MLTrainingSessionParameters(
sessionDirectory: self.sessionDirectoryURL,
reportInterval: 1,
checkpointInterval: 100,
iterations: self.numberOfIterations
)
print("Initializing training session...")
let trainingSession: MLTrainingSession<MLImageClassifier>
if FileManager.default.fileExists(atPath: self.sessionDirectoryURL.path) && isSessionCreated(atPath: self.sessionDirectoryURL.path()) {
do {
trainingSession = try MLImageClassifier.restoreTrainingSession(sessionParameters: sessionParameters)
}
catch {
print("error resuming, exiting.... \(error.localizedDescription)")
fatalError()
}
}
else {
trainingSession = try MLImageClassifier.makeTrainingSession(
trainingData: trainingData,
parameters: modelParameters,
sessionParameters: sessionParameters
)
}
return trainingSession
} catch {
print("Failed to initialize training session: \(error.localizedDescription)")
fatalError()
}
}
I've just tried to update a project that uses SwiftData to Swift 6 using Xcode 16 beta 1, and it's not working due to missing Sendable conformance on a couple of types (MigrationStage and Schema.Version):
struct LocationsMigrationPlan: SchemaMigrationPlan {
static let schemas: [VersionedSchema.Type] = [LocationsVersionedSchema.self]
static let stages: [MigrationStage] = []
}
struct LocationsVersionedSchema: VersionedSchema {
static let models: [any PersistentModel.Type] = [
Location.self
]
static let versionIdentifier = Schema.Version(1, 0, 0)
}
This code results in the following errors:
error: static property 'stages' is not concurrency-safe because non-'Sendable' type '[MigrationStage]' may have shared mutable state
static let stages: [MigrationStage] = []
^
error: static property 'versionIdentifier' is not concurrency-safe because non-'Sendable' type 'Schema.Version' may have shared mutable state
static let versionIdentifier = Schema.Version(1, 0, 0)
^
Am I missing something, or is this a bug in the current seed? I've filed this as FB13862584.
I'm having trouble getting the "Save to Files" option to work with ShareLink. Here's a simple example:
struct Item: Transferable {
public static var transferRepresentation: some TransferRepresentation {
FileRepresentation(exportedContentType: .jpeg) { item in
// Write a jpeg to disk
let url = URL.documentsDirectory.appending(path: "item.jpeg")
let jpegData = UIImage(named: "testImg")!.jpegData(compressionQuality: 1)!
try! jpegData.write(to: url)
return SentTransferredFile(url)
}
}
}
struct ContentView: View {
var body: some View {
ShareLink(item: Item(), preview: SharePreview("Test Item"))
}
}
The ShareSheet presents all of the usual options, but tapping "Save to Files" briefly presents an empty modal before immediately dismissing.
The following errors are logged to the console:
2022-09-12 14:19:57.481592-0700 ExportTest[3468:1374472] [NSExtension] Extension request contains input items but the extension point does not specify a set of allowed payload classes. The extension point's NSExtensionContext subclass must implement `+_allowedItemPayloadClasses`. This must return the set of allowed NSExtensionItem payload classes. In future, this request will fail with an error.
2022-09-12 14:19:58.047009-0700 ExportTest[3468:1374472] [ShareSheet] cancelled request - error: The operation couldn’t be completed. Invalid argument
Sharing finished with error: Error Domain=NSPOSIXErrorDomain Code=22 "Invalid argument" at SwiftUI/SharingActivityPickerBridge.swift:266
2022-09-12 14:19:58.584374-0700 ExportTest[3468:1379359] [AXRuntimeCommon] AX Lookup problem - errorCode:1100 error:Permission denied portName:'com.apple.iphone.axserver' PID:3472 (
0 AXRuntime 0x00000001ca77b024 _AXGetPortFromCache + 932
1 AXRuntime 0x00000001ca77d1d8 AXUIElementPerformFencedActionWithValue + 772
2 UIKit 0x00000002258b3284 3CB83860-AA42-3F9A-9B6E-2954BACE3DAC + 778884
3 libdispatch.dylib 0x0000000105078598 _dispatch_call_block_and_release + 32
4 libdispatch.dylib 0x000000010507a04c _dispatch_client_callout + 20
5 libdispatch.dylib 0x00000001050820fc _dispatch_lane_serial_drain + 988
6 libdispatch.dylib 0x0000000105082e24 _dispatch_lane_invoke + 420
7 libdispatch.dylib 0x000000010508fcac _dispatch_workloop_worker_thread + 740
8 libsystem_pthread.dylib 0x00000001ed9e8df8 _pthread_wqthread + 288
9 libsystem_pthread.dylib 0x00000001ed9e8b98 start_wqthread + 8
)
Additionally, this error is logged when the ShareSheet is first presented (before tapping Save to Files):
[ShareSheet] Couldn't load file URL for Collaboration Item Provider:<NSItemProvider: 0x282a1d650> {types = (
"public.jpeg"
)} : (null)
Has anybody had luck getting custom Transferable representations to work with ShareLink?
Hi everyone,
I need to synchronize the playback of RealityKit Timelines via SharePlay.
To do this I am trying to get the references of the timelines using "AnimationPlaybackController" and "AnimationResource". In my realitykit scene I have configured both an animation (with blender), and a timeline, the animation starts correctly when the realitykit scene starts, the timeline not.
Below the code:
struct ContentView: View {
@State private var subscriptions = [EventSubscription]()
@Environment(AppModel.self)
private var appModel
let rootEntity = Entity()
@State var testEntity: Entity?
@State var testAnimation: AnimationResource?
@State var testController: AnimationPlaybackController?
init() {
CubeComponent.registerComponent()
}
var body: some View {
RealityView { content in
content.add(rootEntity)
if let scene = try? await Entity(named: "Room", in: realityKitContentBundle) {
rootEntity.addChild(scene)
playAnimations(from: content)
}
}
.gesture(SpatialTapGesture().targetedToAnyEntity()
.onEnded({ value in
_ = value.entity.applyTapForBehaviors()
if let testEntity, let testAnimation {
testController = testEntity.playAnimation(testAnimation.repeat())
}
})
)
}
func playAnimations(from content: RealityViewContent) {
subscriptions.append(content.subscribe(to: ComponentEvents.DidAdd.self, componentType: AnimationLibraryComponent.self, { event in
let entity = event.entity
entity.components[AnimationLibraryComponent.self]?.animations.forEach({ (key, value) in
if value.definition is AnimationGroup {
if key == "/Room/TestTimeline" {
let controller = entity.playAnimation(value.repeat())
testEntity = entity
testAnimation = value
appModel.syncronizedAnimations[key] = .init(name: key, animationController: controller, entityName: entity.name)
}
} else {
if entity.name == "SphereInteractable" {
let controller = entity.playAnimation(value.repeat())
appModel.syncronizedAnimations[key] = .init(name: key, animationController: controller, entityName: entity.name)
}
}
})
}))
}
}
the variables testEntity, testAnimation and testController are for testing purposes only. If I try to start the animations in the playAnimations function, only the animation created via blender starts (the one related to the object "SphereInteractable"), the Timeline starts only if I save a reference and I play it with a tap gesture or with a delay of ! seconds with DispatchQueue.asyncAfter called in the onAppear.
is there a better way to handle this? The goal is to have a reference of the AnimationPlaybackController of the timeline, in order to sync the animation via shareplay.
Thanks
While running Swift's SpeechRecognition capabilities I get the error below. However, the app successfully transcribes the audio file.
So am not sure how worried I have to be, as well, would like to know that if when that error occurred, did that mean that the app went to the internet to transcribe that file? Yes, requiresOnDeviceRecognition is set to false.
Would like to know what that error meant, and how much I need to worry about it?
Received an error while accessing com.apple.speech.localspeechrecognition service: Error Domain=kAFAssistantErrorDomain Code=1101 "(null)"
I have two views in a container view as below
@IBOutlet weak var dataDisclosureView: UIStackView! // Main ContainerView
@IBOutlet private weak var titleLabel: UILabel! {
didSet {
titleLabel.text = "Hello"
}
}
@IBOutlet private weak var descriptionLabel: UILabel! {
didSet {
descriptionLabel.text = "World"
}
}
@IBOutlet weak var descriptionView: UIStackView! { // sub container view containing titleLabel and descriptionLabel
didSet {
descriptionView.isAccessibilityElement = true
descriptionView.accessibilityLabel = "Hello"
descriptionView.accessibilityIdentifier = "test_hello"
}
}
@IBOutlet private weak var requestButton: UIButton! {
didSet {
requestButton.isAccessibilityElement = true
requestButton.accessibilityLabel = "Request Button"
requestButton.accessibilityIdentifier = "test_button"
}
}
override func viewDidLoad() {
super.viewDidLoad()
dataDisclosureView.isAccessibilityElement = false
dataDisclosureView.accessibilityElements = [ descriptionView ?? "" ]
if #available(iOS 17.0, *) {
dataDisclosureView.automationElements = [ descriptionView ?? "",
requestButton ?? ""]
} else {
// Fallback on earlier versions
}
let requestButtonAction = UIAccessibilityCustomAction(name: "start",
target: self,
selector: #selector( request))
dataDisclosureView.accessibilityCustomActions = [ requestButtonAction ]
}
Mx issue is I want AccessibilityIdentifers for descriptionLabel,titleLabel,requestButton and hintLabel(For Automation) and accessibility labels for descriptionView and requestButton(VoiceOver Accessibility).
But I am unable to see accessibilityIdentifier for Button, TitleLabel and descriptionLabel in AccessibilityInspector. what am I doing wrong here?
I have an image and label inside UIStackView which are inside a viewcontroller. I want to make my UIView accessible. So I wrote below code:
var image: UIImage!
var myView: UIStackView!
var label : UILabel!
myView.isAccessibilityElement = true
myView.accessibilityLabel = "Hello"
myView.accessiblityIdentifier = "test_view"
image.accessiblityIdentifier = "test_image"
label.accessibilityIdentifier = "test_label"
All are UIKit Elements.
How to expose mvView to accessibility and only children to automation
I tried below two ways, none of them worked:
self.view.accessibilityElements = [myView]
myView.accessibilityElements = []
from apple documentation :
If the object is a view and it’s an accessibility element, and accessibilityElements is empty, the system assigns the list of subviews that have an accessibilityIdentifier to automationElements.
myView.automationElements = [myView,image,label]
from apple documentation :
In some cases, you might want to expose elements for automation but not for accessibility, or vice versa. In a view containing an image with a label under it, for example, you might choose to expose only the label for accessibility. For automation, however, you might include both the image and the label in a test to confirm the both objects exist. In this case, add both the image and the label to automationElements.
I am really going crazy with this since many days. Help is very much appreciated.
Environment
Xcode: 16.1
Swift 6 and SwiftUI for macOS development
macOS Sequoia
I have an app for macOS, and that uses an interactive widget feature.
On macOS Sequoia, the widget does not display anything and widget intent doesn't work either. I tested it on macOS Sonoma and it totally works. I assume it's a macOS bug. The app has been working fine before Sequoia.
Even on Xcode, when I tried to run the widget preview, Failed to load widget. The operation couldn't be completed. (WidgetKit_Simulator.WidgetDocument.Error error 4.).
I could avoid the error by changing version and build numbers, but I still got The operation couldn't be completed. (CHSErrorDomain error 1103.)
How am I able to fix the issue? I wanna at least know if its a bug from the app or macOS Sequoia.
Our team has recently added support to our app for Live Activities where the source of the data is driven from the app itself (not push notifications).
We've noticed a crash happening in our core data code caused by the following error thrown by the addPersistentStore function where it would attempt to recover and eventually crash. Here's an error we created to help us debug that contains the error details:
Domain: CoreData Code: 1 NSLocalizedDescription: Error performing migration for databaseName=mydb.sqlite. Error details=The file couldn’t be saved because you don’t have permission. - userinfo: ["reason": No permissions to create file; code = 1]
After some trouble shooting, we managed to reproduce the issue by doing a hard reboot while we're running a live activity. It appears that when the device starts back up, the Live Activity starts which triggers the app to hit didFinishLaunchingWithOptions which is where we get our Core Data store initialized.
The problem is that our app uses Data Protection using NSFileProtectionCompleteUntilFirstUserAuthentication and we'd prefer to keep it that way.
The Core Data db is present in the app sandbox and we're also seeing logs to suggest a failure trying to access NSUserDefaults as well.
Is there an accepted solution for this? Is it expected that a Live Activity would cause an application to launch prior to the device being unlocked for the first time? Is there a way to change that?
A Swift MacOS works with no problem on Intel or ARM Macs (from 11, BigSur to 15, Sequoia) but recently I learned that is crashes when launched on a Mac which language is set to French.
I'm not saying this setting is causing the issue, but is the most obvious difference observed compared to many other Macs where the App runs with no problem.
The crash occurred in a MacOS intel. See excerpts from crash report below:
Process: MySwiftAPP [626]
Path: /Volumes/VOLUME/*/MySwiftAPP.app/Contents/MacOS/MySwiftAPP
Identifier: Myinfo.MYSwiftAPP
Version: X.Y.01 (1)
Code Type: X86-64 (Native)
Parent Process: launchd [1]
User ID: 501
Date/Time: 2021-01-05 01:47:12.0578 +0100
OS Version: macOS 12.2.1 (21D62)
Report Version: 12
Bridge OS Version: 3.0 (14Y910)
Anonymous UUID: 3579800E-84CC-15C4-2981-320ECF2E1400
Time Awake Since Boot: 62 seconds
System Integrity Protection: enabled
Crashed Thread: 0 Dispatch queue: com.apple.main-thread
Exception Type: EXC_BAD_INSTRUCTION (SIGILL)
Exception Codes: 0x0000000000000001, 0x0000000000000000
Exception Note: EXC_CORPSE_NOTIFY
Termination Reason: Namespace SIGNAL, Code 4 Illegal instruction: 4
Terminating Process: exc handler [626]
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0 MySwiftAPP 0x10c6df5bb 0x10c61d000 + 796091
1 MySwiftAPP 0x10c6be4dc 0x10c61d000 + 660700
2 SwiftUI 0x7ff919a8ff0e closure #1 in AppearanceActionModifier.MergedBox.update() + 72
3 SwiftUI 0x7ff9193d2047 thunk for @escaping @callee_guaranteed () -> () + 12
4 SwiftUI 0x7ff919a91012 partial apply for thunk for @escaping @callee_guaranteed () -> () + 17
5 SwiftUI 0x7ff919bbc028 closure #1 in ViewRendererHost.render(interval:updateDisplayList:) + 2414
6 SwiftUI 0x7ff919ba9fbe ViewRendererHost.render(interval:updateDisplayList:) + 359
7 SwiftUI 0x7ff919c04d56 closure #1 in NSHostingView.layout() + 126
8 SwiftUI 0x7ff919c0dce7 partial apply for thunk for @callee_guaranteed (@guaranteed NSAnimationContext) -> () + 17
9 SwiftUI 0x7ff919c023fd thunk for @escaping @callee_guaranteed (@guaranteed NSAnimationContext) -> () + 36
10 AppKit 0x7ff8113fa152 +[NSAnimationContext runAnimationGroup:] + 55
11 SwiftUI 0x7ff919c04c8a NSHostingView.layout() + 287
12 SwiftUI 0x7ff919c0508a @objc NSHostingView.layout() + 21
13 AppKit 0x7ff811435d7f NSViewLayout + 564
14 AppKit 0x7ff811435851 -[NSView layoutSubtreeWithOldSize:] + 352
15 AppKit 0x7ff811434d68 -[NSView layoutSubtreeIfNeededAndAllowTemporaryEngine:] + 1041
16 AppKit 0x7ff811677f22 +[NSWindow windowWithContentViewController:] + 57
17 SwiftUI 0x7ff9199cd634 specialized WindowStyle.makeWindow(:) + 42
18 SwiftUI 0x7ff919b6c724 AnyWindowStyleStorage.makeWindow(:) + 26
19 SwiftUI 0x7ff91974a736 AppWindowsController.makeWindowController(:restorationID:environment:) + 2314
20 SwiftUI 0x7ff91974887d AppWindowsController.makeMainWindow(info:) + 66
21 SwiftUI 0x7ff9197487c7 AppWindowsController.makeMainWindow() + 424
22 SwiftUI 0x7ff919748067 AppWindowsController.showInitialMainWindow() + 82
23 SwiftUI 0x7ff9194e0c3e AppDelegate.applicationDidFinishLaunching(:) + 85
24 SwiftUI 0x7ff9194e0dd6 @objc AppDelegate.applicationWillFinishLaunching(_:) + 114
25 CoreFoundation 0x7ff80e9a6f23 CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER + 12
26 CoreFoundation 0x7ff80ea443f9 ___CFXRegistrationPost_block_invoke + 49
27 CoreFoundation 0x7ff80ea44376 _CFXRegistrationPost + 496
28 CoreFoundation 0x7ff80e978836 _CFXNotificationPost + 733
29 Foundation 0x7ff80f7c01be -[NSNotificationCenter postNotificationName:object:userInfo:] + 82
30 AppKit 0x7ff8113e761b -[NSApplication _postDidFinishNotification] + 305
31 AppKit 0x7ff8113e736d -[NSApplication _sendFinishLaunchingNotification] + 208
32 AppKit 0x7ff8113e4f40 -[NSApplication(NSAppleEventHandling) _handleAEOpenEvent:] + 541
33 AppKit 0x7ff8113e4b97 -[NSApplication(NSAppleEventHandling) _handleCoreEvent:withReplyEvent:] + 665
34 Foundation 0x7ff80f7eb194 -[NSAppleEventManager dispatchRawAppleEvent:withRawReply:handlerRefCon:] + 308
35 Foundation 0x7ff80f7eb006 _NSAppleEventManagerGenericHandler + 80
36 AE 0x7ff815043d28 0x7ff815038000 + 48424
37 AE 0x7ff815043592 0x7ff815038000 + 46482
38 AE 0x7ff81503c9c7 aeProcessAppleEvent + 419
39 HIToolbox 0x7ff8175fdc42 AEProcessAppleEvent + 54
40 AppKit 0x7ff8113df222 DPSNextEvent + 2064
41 AppKit 0x7ff8113dd3f4 -[NSApplication(NSEvent) nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1411
42 AppKit 0x7ff8113cf919 -[NSApplication run] + 586
43 AppKit 0x7ff8113a37b7 NSApplicationMain + 816
44 SwiftUI 0x7ff9191dad3f specialized runApp(:) + 161
45 SwiftUI 0x7ff919bf9c84 runApp(:) + 164
46 SwiftUI 0x7ff91970191f static App.main() + 63
47 MySwiftAPP 0x10c6be9ae 0x10c61d000 + 661934
48 dyld 0x1134d64fe start + 462
Thread 1:
0 libsystem_pthread.dylib 0x7ff80e8e5fec start_wqthread + 0
Thread 0 crashed with X86 Thread State (64-bit):
rax: 0x0000000200000003 rbx: 0x00007f8db5915210 rcx: 0xfffffffe00000000 rdx: 0x0000000000000003
rdi: 0x00007f8db586b178 rsi: 0x00007ff8518bbf58 rbp: 0x00007ff7b38e0080 rsp: 0x00007ff7b38e0000
r8: 0x0000000000000002 r9: 0x80000000ffffffff r10: 0xfffffffe00000000 r11: 0x0000000000000001
r12: 0x00007f8db586b170 r13: 0x00007f8db586bb40 r14: 0x00007f8db586b290 r15: 0xe800000000000000
rip: 0x000000010c6df5bb rfl: 0x0000000000010297 cr2: 0x00007ff8510288e8
Logical CPU: 0
Error Code: 0x00000000
Trap Number: 6
I am working on creating a file viewer to browse a network directory as a way to introduce myself to iOS app development, and was trying to implement a feature that would allow users to drag and drop both files and folders onto another folder inside of the app to move items around. However, it seems that if the View that is set to draggable, and then the view that is set as the Drop Destination is in the same List, then the Drop Destination will not detect when the draggable view has been dropped onto it. Here is the structure of my code:
List {
Section(header: Text("Folders")) {
ForEach($folders, id: \.id) { $folder in
FolderCardView()
.onDrop(of: [UTType.item], isTargeted: $fileDropTargeted, perform: { (folders, cgPoint) -> Bool in
print("Dropped")
return true
})
}
}
Section(header: Text("Files")) {
ForEach($files, id: \.id) { $file in
FileCardView()
.onDrag({
let folderProvider = NSItemProvider(object: file)
return folderProvider
})
}
}
}
I have verified that the issue comes down to the list, because if I move both of the ForEach loops out on their own, or even into their own respective lists, the code works perfectly. I have not only tested this with the older .onDrop and .onDrag modifiers as shown above, but also the newer .draggable and .dropDestination modifiers, and the result is the same.
Does anyone know if this is intended behavior? I really like the default styling that the List element applies to other elements within, so I am hoping that it might just be a bug or an oversight. Thanks!