My app experiencing a rare crash that I am unable to reproduce and am struggling to make progress with:
Thread 0 name:
Thread 0 Crashed:
0 libobjc.A.dylib 0x00000001926c3c20 objc_msgSend + 32 (:-1)
1 Foundation 0x00000001997357b4 __NSThreadPerformPerform + 264 (NSThread.m:1084)
2 CoreFoundation 0x000000019a82b834 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 (CFRunLoop.c:1957)
3 CoreFoundation 0x000000019a82b7c8 __CFRunLoopDoSource0 + 176 (CFRunLoop.c:2001)
4 CoreFoundation 0x000000019a8292f8 __CFRunLoopDoSources0 + 340 (CFRunLoop.c:2046)
5 CoreFoundation 0x000000019a828484 __CFRunLoopRun + 828 (CFRunLoop.c:2955)
6 CoreFoundation 0x000000019a827cd8 CFRunLoopRunSpecific + 608 (CFRunLoop.c:3420)
7 GraphicsServices 0x00000001df2751a8 GSEventRunModal + 164 (GSEvent.c:2196)
8 UIKitCore 0x000000019ce61ae8 -[UIApplication _run] + 888 (UIApplication.m:3713)
9 UIKitCore 0x000000019cf15d98 UIApplicationMain + 340 (UIApplication.m:5303)
10 <redacted> 0x000000010287af04 main + 64 (AppDelegate.swift:15)
11 dyld 0x00000001bdfff154 start + 2356 (dyldMain.cpp:1298)
I have done a fair amount of digging, looking at other similar crashes and at this:
https://developer.apple.com/forums/thread/92102
but being unable to reproduce is quite limiting.
I found this very similar issue with useful info on finding which function was being called:
https://forums.developer.apple.com/forums/thread/67763
But in my case, the x1 (and x2) register values seem to point to an area outside of the ranges in the "Binary Images" section..
I've attached an example of a full crash report (with the app name redacted):
2024-10-30_20-44-26.7576_+0000-98e2ef3ee4472b9eb237b0780e8fa0162e1aa7f4.crash
Any help would be greatly appreciated.
Swift
RSS for tagSwift is a powerful and intuitive programming language for Apple platforms and beyond.
Posts under Swift tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Hello, I wanted to sync my Swift Data App with iCloud. I provided default values to all my models, made very relationship between my models optional. Then, at Signing and Capabilities, I finally added Background Modes (and checked Remote notifications) and iCloud (and checked CloudKit and added a container with my bundle id). Now I receive these errors every time I run my app on a device that is connect to iCloud
CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _recoverFromError:withZoneIDs:forStore:inMonitor:](2620): <NSCloudKitMirroringDelegate: 0x302de80f0> - Failed to recover from error: CKErrorDomain:15
Recovery encountered the following error: (null):0
CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _finishedRequest:withResult:](3582): Finished request: <NSCloudKitMirroringDelegateSetupRequest: 0x3031d4460> 53CB1DFC-E589-4945-8AF1-36126756110B with result: <NSCloudKitMirroringResult: 0x301c79320> storeIdentifier: 41F2B808-5C97-44B3-BC28-5534FEBCCF2C success: 0 madeChanges: 0 error: <CKError 0x301c98870: "Partial Failure" (2/1011); "Failed to modify some record zones"; uuid = 044262C6-5136-4989-823C-B0430F7B87DC; container ID = "iCloud.lu.yansoisson.blip-notes"; partial errors: {
com.apple.coredata.cloudkit.zone:__defaultOwner__ = <CKError 0x301c7a9a0: "Server Rejected Request" (15/2000); op = 15C2EFE32CB459E1; uuid = 044262C6-5136-4989-823C-B0430F7B87DC>
}>
CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate checkAndExecuteNextRequest](3551): <NSCloudKitMirroringDelegate: 0x302de80f0>: Checking for pending requests.
CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate checkAndExecuteNextRequest]_block_invoke(3567): <NSCloudKitMirroringDelegate: 0x302de80f0>: No more requests to execute.
CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate recoverFromError:](2310): <NSCloudKitMirroringDelegate: 0x302de80f0> - Attempting recovery from error: <CKError 0x301c98870: "Partial Failure" (2/1011); "Failed to modify some record zones"; uuid = 044262C6-5136-4989-823C-B0430F7B87DC; container ID = "iCloud.lu.yansoisson.blip-notes"; partial errors: {
com.apple.coredata.cloudkit.zone:__defaultOwner__ = <CKError 0x301c7a9a0: "Server Rejected Request" (15/2000); op = 15C2EFE32CB459E1; uuid = 044262C6-5136-4989-823C-B0430F7B87DC>
}>
Here's the debug message that appears first when I start the app
CoreData: debug: CoreData+CloudKit: -[PFCloudKitOptionsValidator validateOptions:andStoreOptions:error:](36): Validating options: <NSCloudKitMirroringDelegateOptions: 0x3023ec6e0> containerIdentifier:iCloud.lu.yansoisson.blip-notes databaseScope:Private ckAssetThresholdBytes:<null> operationMemoryThresholdBytes:<null> useEncryptedStorage:NO useDeviceToDeviceEncryption:NO automaticallyDownloadFileBackedFutures:NO automaticallyScheduleImportAndExportOperations:YES skipCloudKitSetup:NO preserveLegacyRecordMetadataBehavior:NO useDaemon:YES apsConnectionMachServiceName:<null> containerProvider:<PFCloudKitContainerProvider: 0x3010e62d0> storeMonitorProvider:<PFCloudKitStoreMonitorProvider: 0x3010e62e0> metricsClient:<PFCloudKitMetricsClient: 0x3010e62f0> metadataPurger:<PFCloudKitMetadataPurger: 0x3010e6300> scheduler:<null> notificationListener:<null> containerOptions:<null> defaultOperationConfiguration:<null> progressProvider:<NSPersistentCloudKitContainer: 0x300785440> test_useLegacySavePolicy:YES archivingUtilities:<PFCloudKitArchivingUtilities: 0x3010e6310> bypassSchedulerActivityForInitialImport:NO bypassDasdRateLimiting:NO activityVouchers:(
)
storeOptions: {
NSInferMappingModelAutomaticallyOption = 1;
NSMigratePersistentStoresAutomaticallyOption = 1;
NSPersistentCloudKitContainerOptionsKey = "<NSPersistentCloudKitContainerOptions: 0x3036f0ea0>";
NSPersistentHistoryTrackingKey = 1;
NSPersistentStoreMirroringOptionsKey = {
NSPersistentStoreMirroringDelegateOptionKey = "<NSCloudKitMirroringDelegate: 0x302de80f0>";
};
NSPersistentStoreRemoteChangeNotificationOptionKey = 1;
}
CoreData: debug: CoreData+CloudKit: -[NSCloudKitMirroringDelegate observeChangesForStore:inPersistentStoreCoordinator:](427): <NSCloudKitMirroringDelegate: 0x302de80f0>: Observing store: <NSSQLCore: 0x10214ca00> (URL: file:///var/mobile/Containers/Data/Application/780A6276-3BE4-458E-BD2D-EC304B123111/Library/Application%20Support/default.store)
CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _setUpCloudKitIntegration:](589): <NSCloudKitMirroringDelegate: 0x302de80f0>: Successfully enqueued setup request: <NSCloudKitMirroringDelegateSetupRequest: 0x3031d4460> 53CB1DFC-E589-4945-8AF1-36126756110B
CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate checkAndExecuteNextRequest](3551): <NSCloudKitMirroringDelegate: 0x302de80f0>: Checking for pending requests.
CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate checkAndExecuteNextRequest]_block_invoke(3564): <NSCloudKitMirroringDelegate: 0x302de80f0>: Executing: <NSCloudKitMirroringDelegateSetupRequest: 0x3031d4460> 53CB1DFC-E589-4945-8AF1-36126756110B
CoreData: warning: CoreData+CloudKit: -[PFCloudKitSetupAssistant _checkAccountStatus:]_block_invoke(342): Fetched account info for store 41F2B808-5C97-44B3-BC28-5534FEBCCF2C: <CKAccountInfo: 0x3007bbb80; accountStatus=Available, accountPartition=Prod, deviceToDeviceEncryptionAvailability=(account|device), hasValidCredentials=true, walrus=Enabled, needsToVerifyTerms=false, accountAccessAuthorization=Yes, validationCounter=545>
(null)
CoreData: warning: CoreData+CloudKit: -[PFCloudKitSetupAssistant _checkUserIdentity:]_block_invoke(1446): Fetched user recordID for store 41F2B808-5C97-44B3-BC28-5534FEBCCF2C: <CKRecordID: 0x3012ddbc0; recordName=_e002d189d325132b7dae12ad045e5d76, zoneID=_defaultZone:__defaultOwner__>
(null)
Does anyone know how to solve this issue since I have done everything exactly like mentioned in multiple tutorials and blogs?
Thanks
I'm developing an authorization plugin for macOS and encountering a problem while trying to store a password in the system keychain (file-based keychain). The error message I'm receiving is:
Failed to add password: Write permissions error.
Operation status: -61
Here’s the code snippet I’m using:
import Foundation
import Security
@objc class KeychainHelper: NSObject {
@objc static func systemKeychain() -> SecKeychain? {
var searchListQ: CFArray? = nil
let err = SecKeychainCopyDomainSearchList(.system, &searchListQ)
guard err == errSecSuccess else {
return nil
}
let searchList = searchListQ! as! [SecKeychain]
return searchList.first
}
@objc static func storePasswordInSpecificKeychain(service: String, account: String, password: String) -> OSStatus {
guard let systemKeychainRef = systemKeychain() else {
print("Error: Could not get a reference to the system keychain.")
return errSecNoSuchKeychain
}
guard let passwordData = password.data(using: .utf8) else {
print("Failed to convert password to data.")
return errSecParam
}
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
kSecValueData as String: passwordData,
kSecUseKeychain as String: systemKeychainRef // Specify the System Keychain
]
let status = SecItemAdd(query as CFDictionary, nil)
if status == errSecSuccess {
print("Password successfully added to the System Keychain.")
} else if status == errSecDuplicateItem {
print("Item already exists. Consider updating it instead.")
} else {
print("Failed to add password: \(SecCopyErrorMessageString(status, nil) ?? "Unknown error" as CFString)")
}
return status
}
}
I am callling storePasswordInSpecificKeychain through the objective-c code. I also used privileged in the authorizationDb (system.login.console).
Are there specific permissions that need to be granted for an authorization plugin to modify the system keychain?
Hi,
I'm working on integrating iCloud Drive functionality into my app. I noticed that the folder for my app appears under /Users/USERNAME/Library/Mobile Documents/MY_CONTAINER, but it doesn't show up in iCloud Drive.
Am I missing a step in the setup or configuration? Any guidance would be appreciated!
Thanks!
I've been struggling with a problem for the past couple of weeks, and I can't seem to figure out the cause. I'm developing an app that allows users to easily switch languages on macOS. The app is ready, and I submitted it for review, but the problem is that Apple has been unable to approve it for the past two weeks due to an issue.
Upon launching the app, an empty window/container appears, but I cannot reproduce this issue on my own Macs (M1, M2, M3). On my machines, the app works perfectly and launches without the empty window appearing.
Does anyone know how I can identify and resolve this issue? I’ve attached a screenshot of the empty window that needs to be removed from the code, as well as a snippet of the code that might be responsible for it.
I would greatly appreciate any advice or suggestions on how to fix this, as I’m unable to reproduce the error on my end.
Thanks in advance for your help!
@main
struct LanguageSwitcherApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
var body: some Scene {
Settings {
EmptyView()
}
.commands {
CommandGroup(after: .appInfo) {
Button("Show Language Switcher") {
appDelegate.showLanguageSwitcher()
}
}
}
}
}
class AppDelegate: NSObject, NSApplicationDelegate {
private var statusItem: NSStatusItem?
private var languageSwitcherPanel: LanguageSwitchPanel?
func applicationDidFinishLaunching(_ notification: Notification) {
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
if let button = statusItem?.button {
button.image = NSImage(named: "icon_top")
button.action = #selector(showMenu)
button.target = self
}
showLanguageSwitcher()
}
@objc private func showMenu() {
let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Close Type Switch", action: #selector(closeApp), keyEquivalent: "q"))
statusItem?.menu = menu
statusItem?.button?.performClick(nil)
statusItem?.menu = nil
}
func showLanguageSwitcher() {
guard languageSwitcherPanel == nil else { return }
let panel = LanguageSwitchPanel()
let hostingController = NSHostingController(rootView: LanguageSwitchView())
panel.contentView = hostingController.view
panel.makeKeyAndOrderFront(nil)
NSApp.activate(ignoringOtherApps: true)
languageSwitcherPanel = panel
}
@objc private func closeApp() {
NSApp.terminate(nil)
}
}
Screenshot: https://ibb.co/hynrgyw
I tried testing the app on my MacBook models (M1, M2, M3) and all of them functioned as expected, launching the app without any additional windows appearing. I also checked the code for any unintended window launches or containers and could not find any issues.
I expected the app to launch without any extra empty windows or containers, but when Apple tested it, they encountered an issue with an empty window appearing upon launch.
DeviceActivityReport presents statistics for a device: https://developer.apple.com/documentation/deviceactivity/deviceactivityreport
The problem: DeviceActivityReport can present statistics with a delay for a parent device (when DeviceActivityReport is presenting, the DeviceActivityReportExtension is called to process the statistics). One possible solution is to call DeviceActivityReport periodically throughout the day in a child device. However, the app will not be available all day. Is there any way to run DeviceActivityReport in the background?
I have tried the following approach, but it didn’t work (DeviceActivityReportExtension didnt call):
let hostingController: UIHostingController? = .init(rootView: DeviceActivityReport(context, filter: filter))
hostingController?.view.frame = .init(origin: .zero, size: .init(width: 100, height: 100))
hostingController?.beginAppearanceTransition(true, animated: false)
hostingController?.loadView()
hostingController?.viewDidLoad()
try? await Task.sleep(for: .seconds(0.5))
hostingController?.viewWillAppear(true)
hostingController?.viewWillLayoutSubviews()
try? await Task.sleep(for: .seconds(0.5))
hostingController?.viewDidAppear(true)
try? await Task.sleep(for: .seconds(0.5))
hostingController?.didMove(toParent: rootVC)
try? await Task.sleep(for: .seconds(0.5))
hostingController?.viewWillLayoutSubviews()
hostingController?.viewDidLayoutSubviews()
hostingController?.view.layoutIfNeeded()
hostingController?.view.layoutSubviews()
hostingController?.endAppearanceTransition()
Is there any way to run DeviceActivityReport in the background? (when app is not visible/closed). The main problem is call DeviceActivityReport
My visionOS app can install custom fonts.
My visionOS app also lists these fonts as available within the application, and I can see them in a list using CTFontManagerCopyAvailableFontFamilyNames
I manually track which fonts have been installed.
So far, so good. But here’s my problem: When a user uninstalls a font via Settings, I have no way to tell. That’s because CTFontManagerCopyAvailableFontFamilyNames will still list that font because it’s still available within the application.
How can I track these changes in my app when a font is uninstalled via Settings?
When i create a intance of swift String :
Let str = String ("Hello")
As swift String are immutable, and when we mutate the value of these like:
str = "Hello world ......." // 200 characters
Swift should internally allocate new memory and copy the content to that buffer for update .
But when i checked the addresses of original and modified str, both are same?
Can you help me understand how this allocation and mutation working internally in swift String?
When user enters in a textfield, is the input of textfield gets stored in a String ?
If yes, then String in swift being immutable, as user keeps on typing does new memory for storing that text gets allocated with each key stroke ?
And when we read users input by using delegate method textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) from textfield.text, we get users input in a String. Is it same storage as used by textfield for storing the user input on key stroke or is it some other storage with copy of the user's input in it?
Or is UItextfield using a diffrent data structure (buffer) for storing the user input and when we do textfield.text, it gives a copy of data stored in original buffer?
When call:
[UITabBarController setViewControllers:animated:]
It crashed and raise an Fatal Exception:
Fatal Exception: NSInternalInconsistencyException Attempting to select a view controller that isn't a child! (null)
the crash stack is:
Fatal Exception: NSInternalInconsistencyException
0 CoreFoundation 0x8408c __exceptionPreprocess
1 libobjc.A.dylib 0x172e4 objc_exception_throw
2 Foundation 0x82215c _userInfoForFileAndLine
3 UIKitCore 0x38a468 -[UITabBarController transitionFromViewController:toViewController:transition:shouldSetSelected:]
4 UIKitCore 0x3fa8a4 -[UITabBarController _setSelectedViewController:performUpdates:]
5 UIKitCore 0x3fa710 -[UITabBarController setSelectedIndex:]
6 UIKitCore 0x8a5fc +[UIView(Animation) performWithoutAnimation:]
7 UIKitCore 0x3e54e0 -[UITabBarController _setViewControllers:animated:]
8 UIKitCore 0x45d7a0 -[UITabBarController setViewControllers:animated:]
And it appear sometimes, what's the root cause?
I am working on an application that supports both Arabic and English languages, allowing the user to switch between them.
The problem occurs when I switch the language to Arabic. I have restricted the user to only use the English keyboard, not the Arabic keyboard.
Whenever I enter a number in the TextInput, it automatically converts the number to the Arabic numeral font.
I want to display English numerals even when the language is set to Arabic in the TextInput view.
I have a SwiftUI app that I've been working on in XCode 16.1. The project builds and runs in the simulators, on my mac and on my iPhone/iPad without any issues. I'm also able to build my unit test project and run them without any errors. The project has zero warnings in it.
When I go to the Edit Schemes options and change the Run scheme to be a Release build with the Debug Executable unchecked I get a compiler error:
Command SwiftCompile failed with a nonzero exit code
I've attempted this Release Run with the following target devices in XCode:
My iPhone 15 Pro Max (iOS 18.2 Beta 3)
MacBook Air (M1) (15.2 Beta)
iPhone 16 Simulator (iOS 18.1)
Any iOS Simulator Device (arm64, x86_64)
All 3 of these target have the same issue. Normally I would just debug the error from the logs but when I look at the build output I can't see any information in the log to tell me what happened. It looks like the source files are sent into the SwiftCompiler and the compiler fails without bubbling up the issue.
I've provided the full error log export as a Gist HERE due to it's size. Is there anything in the log I'm missing? Is there a way for me to turn on more verbose logging during compilation of a Release Build?
I created a brand new Multiplatform App in XCode and I added all of my source files to it. No project configuration settings were changed. I could build it successfully with the debug configuration. I then changed it to the Release configuration and experienced the same error. I can create another fresh project and make the same release configuration with none of my source files in it and get a successful build. I
t seems there is something wrong with my source files and the release configuration but the compiler doesn't indicate what. I'm lost at this point as I can't figure out how to get a release build and can't seem to find any indication as to why.
Hi, I'm trying to modify the ScreenCaptureKit Sample code by implementing an actor for Metal rendering, but I'm experiencing issues with frame rendering sequence.
My app workflow is:
ScreenCapture -> createFrame -> setRenderData
Metal draw callback -> renderAsync (getData from renderData)
I've added timestamps to verify frame ordering, I also using binarySearch to insert the frame with timestamp, and while the timestamps appear to be in sequence, the actual rendering output seems out of order.
// ScreenCaptureKit sample
func createFrame(for sampleBuffer: CMSampleBuffer) async {
if let surface: IOSurface = getIOSurface(for: sampleBuffer) {
await renderer.setRenderData(surface, timeStamp: sampleBuffer.presentationTimeStamp.seconds)
}
}
class Renderer {
...
func setRenderData(surface: IOSurface, timeStamp: Double) async {
_ = await renderSemaphore.getSetBuffers(
isGet: false,
surface: surface,
timeStamp: timeStamp
)
}
func draw(in view: MTKView) {
Task {
await renderAsync(view)
}
}
func renderAsync(_ view: MTKView) async {
guard await renderSemaphore.beginRender() else { return }
guard let frame = await renderSemaphore.getSetBuffers(
isGet: true, surface: nil, timeStamp: nil
) else {
await renderSemaphore.endRender()
return }
guard let texture = await renderSemaphore.getRenderData(
device: self.device,
surface: frame.surface) else {
await renderSemaphore.endRender()
return
}
guard let commandBuffer = _commandQueue.makeCommandBuffer(),
let renderPassDescriptor = await view.currentRenderPassDescriptor,
let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) else {
await renderSemaphore.endRender()
return
}
// Shaders ..
renderEncoder.endEncoding()
commandBuffer.addCompletedHandler() { @Sendable (_ commandBuffer)-> Swift.Void in
updateFPS()
}
// commit frame in actor
let success = await renderSemaphore.commitFrame(
timeStamp: frame.timeStamp,
commandBuffer: commandBuffer,
drawable: view.currentDrawable!
)
if !success {
print("Frame dropped due to out-of-order timestamp")
}
await renderSemaphore.endRender()
}
}
actor RenderSemaphore {
private var frameBuffers: [FrameData] = []
private var lastReadTimeStamp: Double = 0.0
private var lastCommittedTimeStamp: Double = 0
private var activeTaskCount = 0
private var activeRenderCount = 0
private let maxTasks = 3
private var textureCache: CVMetalTextureCache?
init() {
}
func initTextureCache(device: MTLDevice) {
CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, device, nil, &self.textureCache)
}
func beginRender() -> Bool {
guard activeRenderCount < maxTasks else { return false }
activeRenderCount += 1
return true
}
func endRender() {
if activeRenderCount > 0 {
activeRenderCount -= 1
}
}
func setTextureLoaded(_ loaded: Bool) {
isTextureLoaded = loaded
}
func getSetBuffers(isGet: Bool, surface: IOSurface?, timeStamp: Double?) -> FrameData? {
if isGet {
if !frameBuffers.isEmpty {
let frame = frameBuffers.removeFirst()
if frame.timeStamp > lastReadTimeStamp {
lastReadTimeStamp = frame.timeStamp
print(frame.timeStamp)
return frame
}
}
return nil
} else {
// Set
let frameData = FrameData(
surface: surface!,
timeStamp: timeStamp!
)
// insert to the right position
let insertIndex = binarySearch(for: timeStamp!)
frameBuffers.insert(frameData, at: insertIndex)
return frameData
}
}
private func binarySearch(for timeStamp: Double) -> Int {
var left = 0
var right = frameBuffers.count
while left < right {
let mid = (left + right) / 2
if frameBuffers[mid].timeStamp > timeStamp {
right = mid
} else {
left = mid + 1
}
}
return left
}
// for setRenderDataNormalized
func tryEnterTask() -> Bool {
guard activeTaskCount < maxTasks else { return false }
activeTaskCount += 1
return true
}
func exitTask() {
activeTaskCount -= 1
}
func commitFrame(timeStamp: Double,
commandBuffer: MTLCommandBuffer,
drawable: MTLDrawable) async -> Bool {
guard timeStamp > lastCommittedTimeStamp else {
print("Drop frame at commit: \(timeStamp) <= \(lastCommittedTimeStamp)")
return false
}
commandBuffer.present(drawable)
commandBuffer.commit()
lastCommittedTimeStamp = timeStamp
return true
}
func getRenderData(
device: MTLDevice,
surface: IOSurface,
depthData: [Float]
) -> (MTLTexture, MTLBuffer)? {
let _textureName = "RenderData"
var px: Unmanaged<CVPixelBuffer>?
let status = CVPixelBufferCreateWithIOSurface(kCFAllocatorDefault, surface, nil, &px)
guard status == kCVReturnSuccess, let screenImage = px?.takeRetainedValue() else {
return nil
}
CVMetalTextureCacheFlush(textureCache!, 0)
var texture: CVMetalTexture? = nil
let width = CVPixelBufferGetWidthOfPlane(screenImage, 0)
let height = CVPixelBufferGetHeightOfPlane(screenImage, 0)
let result2 = CVMetalTextureCacheCreateTextureFromImage(
kCFAllocatorDefault,
self.textureCache!,
screenImage,
nil,
MTLPixelFormat.bgra8Unorm,
width,
height,
0, &texture)
guard result2 == kCVReturnSuccess,
let cvTexture = texture,
let mtlTexture = CVMetalTextureGetTexture(cvTexture) else {
return nil
}
mtlTexture.label = _textureName
let depthBuffer = device.makeBuffer(bytes: depthData, length: depthData.count * MemoryLayout<Float>.stride)!
return (mtlTexture, depthBuffer)
}
}
Above's my code - could someone point out what might be wrong?
Hello,
I am using Xcode 16.1 (16B40) on MacOS Sequoia 15.1.0 using a Macbook pro M1 Max
I am developing an app for iOS 17 and 18 using SwiftUI
I created UITests to take the screenshots for the appStore on the simulator
The tests run well and all of them are succeded
The problem appears when I try to get the screenshot files from the xcresult files after the test. There is not any screenshot inside it.
I found a data folder and a Info.plist file. In the data folder there are a lot of files with this pattern data.03zD4C6IGFFthK14NwA8mNvcwFHT16g6Tl40Tl1YmBC1bNh6d0YIcnWKyUaQPDXoa8fYo6C3Xcv8xvMtE3_NEXA== and other files with this pattern refs.03zD4C6IGFFthK14NwA8mNvcwFHT16g6Tl40Tl1YmBC1bNh6d0YIcnWKyUaQPDXoa8fYo6C3Xcv8xvMtE3_NEXA==
Ok, I tryed to use fastlane to automatize the screenshots but the problem is still present. The xcresult files have not any png file.
I had no problems doing this action (getting screenshots from a xcresult file) in previous versions of MacOS and Xcode in my current machine.
I just updated my machine to MacOS Sequoia 15.1.1 and the problem is still present
Honestly I don't know how to fix this situation.
With Xcode 15 I had not any problem with that but I am not sure if Xcode 16.0 was runing without problems because I didn't need to use this functionality in those months
Here is my code for a UITest:
import XCTest
final class ScreenshotsUITests: XCTestCase {
let app = XCUIApplication()
let device = "iPhone16"
override func setUpWithError() throws {
continueAfterFailure = true
}
override func tearDownWithError() throws {}
@MainActor
func testEnglishScreens() throws {
let lang = "en"
app.launchArguments.append("UITestMode")
app.launchArguments += ["-AppleLanguages", "(en)"]
app.launchArguments += ["-AppleLocale", "en_US"]
app.launch()
executeTestsForMenus(lang: lang, backLabel: "Back")
executeTestForMatch(lang: lang)
}
@MainActor
func testSpanishScreens() throws {
let lang = "es"
app.launchArguments.append("UITestMode")
app.launchArguments += ["-AppleLanguages", "(es)"]
app.launchArguments += ["-AppleLocale", "es_ES"]
app.launch()
executeTestsForMenus(lang: lang, backLabel: "Atrás")
executeTestForMatch(lang: lang)
}
private func executeTestForMatch(lang: String) {
let startButton = app.buttons["start-button"]
startButton.tap()
let key4 = app.buttons["key-4"]
XCTAssertTrue(key4.waitForExistence(timeout: 30), "Key 4 in match screen is not found")
key4.tap()
let key2 = app.buttons["key-2"]
XCTAssertTrue(key2.exists, "Key 2 in match screen is not found")
key2.tap()
makeScreenShot("playing", lang: lang)
let closeButton = app.buttons["close-button"]
XCTAssertTrue(closeButton.exists, "Close button in match screen is not found")
closeButton.tap()
}
private func executeTestsForMenus(lang: String, backLabel: String) {
let mainHeader = app.staticTexts["Math match"]
XCTAssertTrue(mainHeader.exists, "Header in main screen is not found")
makeScreenShot("mainMenu", lang: lang)
let settingsButton = app.buttons["settings-button"]
XCTAssertTrue(settingsButton.exists, "Settings button in main screen is not found")
settingsButton.tap()
makeScreenShot("Settings", lang: lang)
let backButton = app.buttons[backLabel]
XCTAssertTrue(backButton.exists, "Back button in match screen is not found")
backButton.tap()
let helpButton = app.buttons["help-button"]
XCTAssertTrue(helpButton.exists, "Help button in main screen is not found")
helpButton.tap()
makeScreenShot("Help", lang: lang)
backButton.tap()
let scoreButton = app.buttons["score-button"]
XCTAssertTrue(scoreButton.exists, "Scores button in main screen is not found")
scoreButton.tap()
makeScreenShot("Scores", lang: lang)
backButton.tap()
let playButton = app.buttons["play-button"]
XCTAssertTrue(playButton.exists, "Play button in main screen is not found")
playButton.tap()
makeScreenShot("matchBuilder", lang: lang)
let startButton = app.buttons["start-button"]
XCTAssertTrue(startButton.exists, "Start button in match builder screen is not found")
}
private func makeScreenShot(_ name: String, lang: String) {
takeScreenshot(app, named: "\(lang)-\(name)-\(device)")
}
}
import XCTest
extension XCTestCase {
func takeScreenshot(_ app: XCUIApplication, named name: String, fullScreen: Bool = false) {
let screenshot: XCUIScreenshot
if fullScreen {
screenshot = app.windows.firstMatch.screenshot()
} else {
screenshot = XCUIScreen.main.screenshot()
}
let screenshotAttachment = XCTAttachment(
uniformTypeIdentifier: "public.png",
name: "screenshot-\(name).png",
payload: screenshot.pngRepresentation,
userInfo: nil)
screenshotAttachment.lifetime = .keepAlways
add(screenshotAttachment)
}
}
and here is the content of my testplan file:
{
"configurations" : [
{
"id" : "35BC7C0B-9A5A-4027-9F30-36958C4C1AAF",
"name" : "Test Scheme Action",
"options" : {
"preferredScreenCaptureFormat" : "screenshot",
"testExecutionOrdering" : "random",
"uiTestingScreenshotsLifetime" : "keepAlways",
"userAttachmentLifetime" : "keepAlways"
}
}
],
"defaultOptions" : {
"targetForVariableExpansion" : {
"containerPath" : "container:myAppProject.xcodeproj",
"identifier" : "B27D1B022CA00314001A259B",
"name" : "MyAppProject"
}
},
"testTargets" : [
{
"parallelizable" : true,
"target" : {
"containerPath" : "container:MyAppProject.xcodeproj",
"identifier" : "B27D1B122CA00315001A259B",
"name" : "MyAppProjectTests"
}
},
{
"parallelizable" : true,
"target" : {
"containerPath" : "container:MyAppProject.xcodeproj",
"identifier" : "B27D1B1C2CA00315001A259B",
"name" : "MyAppProjectUITests"
}
}
],
"version" : 1
}
I made tests with old projects in my machine and those projects have the same problem with screenshot files in the xcresult bundles
I don't know if the problem is in my machine, my Xcode, MacOS or other ting. I don't know how to fix this problem
Please, can anyone help me?
Thanks in advance
Is there a way to know the event of user unlocking on iOS Device in Application?
Hi team,
We're using CocoaPods in our project and we noticed the compiler fails to build certain targets saying it's "Missing required module 'x'" when trying to build them in Swift 6:
We realized the modules the compiler is complaining about are pod dependencies required by the other target dependencies, and that this error will only appear when building with Swift 6 unless such dependencies are described on the Podfile as direct dependencies of the target, or we include them in the framework search paths. For example, the error in the image above will show if module 'X' import 'Y' and 'Y' imports 'CocoaLumberJack' and we don't specify a direct dependency between 'X' and 'CocoaLumberJack'.
Regardless of the fact that we can manually add the missing module location to the target search paths, we'd like to understand why we're facing this issue in the first place, what changed between Swift 5 and Swift 6 that's requiring us now to explicitly describe these dependencies. I'd appreciate if someone could tell us more about this. We're particularly interested on knowing if this is an intentional change and how to handle it properly.
Thanks
Hi the app crashes with message: **thunk for @escaping @callee_guaranteed (@guaranteed NSURLSessionTask) -> () + 48 (:0) ** and I am unable to understand what it means or why is it happening. Want to understand the reason for the message.
Thank you.
Hi,
I'm developing a musicKit integration in my iOS App, and I want to select songs from recently played (done it), the problem is that the queue is not auto-generated and the user have to select other song if they want to go forward.
There is any method to ask for similar songs, or recommended songs, from a song that the user has already selected?
It will be really great :)
Also if you know it... There is any publisher for the music duration or I need to do a timer?? Thanks.
David.
I have a swiftui view with Button(intent: ) and using UIHostingViewcontroller to use it in UIKit. The problem is that button not works in uikit but normal button(without intent works)
Hello everyone,
I'm currently working through this example project Exploring object tracking with ARKit to learn how to use Object Tracking with visionOS.
I was able to modify the example project to overlay a different model onto the detected object. However, with the example code, I'm only able to track 1 instance of the trained object at a time. I'm wondering if there is a way to track multiple instances of 1 object?
For example, I have a usdz model of a box, then trained that box for object tracking, I'm able to overlay a model of a chair over that box once it's detected. But now, I have multiple copies of that same box, and I want to arrange them so that when I wear the Vision Pro, I can see the chairs arranged however I want.
I'm still new to visionOS development, so I'm not sure if there's a way to accomplish that by just training 1 object and having copies of it.
If it helps, this is my current modification to overlay a virtual object ontop of a detected object.
func loadReferenceObjects() async -> [ReferenceObject] {
// Get a list of all reference object files in the app's main bundle and attempt to load each.
var referenceObjectFiles: [String] = []
if let resourcesPath = Bundle.main.resourcePath {
print("resource path: \(resourcesPath)")
try? referenceObjectFiles = FileManager.default.contentsOfDirectory(atPath: resourcesPath).filter { $0.hasSuffix(".referenceobject") }
}
await withTaskGroup(of: Void.self) { group in
for file in referenceObjectFiles {
let objectURL = Bundle.main.bundleURL.appending(path: file)
group.addTask {
// get the file name
let fileNameWithoutExtension = (file as NSString).deletingPathExtension
// load each ref objs as task
await self.loadSingleReferenceObject(url: objectURL, fileName: fileNameWithoutExtension)
}
}
}
return self.referenceObjects
}
// Private helper method to load a single object
// and assign entity to it.
private func loadSingleReferenceObject(url: URL, fileName: String) async {
var referenceObject: ReferenceObject
do {
print("Loading reference object from \(url)")
// Load the file as a `ReferenceObject` - this can take a while for larger objects.
try await referenceObject = ReferenceObject(from: url)
} catch {
fatalError("Failed to load reference object with error \(error)")
}
// add the ref obj to the ref objs array
self.referenceObjects.append(referenceObject)
// entity with each file
var model: Entity = Entity()
// add entity according to the file name
switch fileName {
// Box1 ref obj binds with Chair1
case "Box1":
// try to load the model
do {
try await model = Entity(named: "chair1", in: realityKitContentBundle)
} catch {
print("Failed to load chair1")
}
// Box2 ref obj binds with Chair2
case "Box2":
// try to load the model
do {
try await model = Entity(named: "chair2", in: realityKitContentBundle)
} catch {
print("Failed to load chair2")
}
default:
print("no model associated with this file name: \(fileName)")
break
}
// map entity to ref objs
usdzPerReferenceObject[referenceObject.id] = model
}
Any help or suggestions would be greatly appreciated.
Thank you.