I am experiencing memory leaks in my iOS app that seem to be related to an issue between UIInputView and _UIInputViewContent. After using the memory graph, I'm seeing that instances of these objects aren't being deallocated properly.
The UIInputViewController whichs holds the inputView is being deallocated properly along with its subviews.I have tried to remove all of UIInputViewController's subviews and their functions but the uiInputView is not being deallocated.
The current setup of my app is a collectionView with multiple cell,each possessing a textfield with holds a UIInputViewController.When i scroll up or down,the views are being reused as expected and the number of UIInputViewController stays consistent with the number of textfields.However the number of inputView keeps increasing referencing solely _UIInputViewContent.
class KeyboardViewController: UIInputViewController {
// Callbacks
var key1: ((String) -> Void)?
var key2: (() -> Void)?
var key3: (() -> Void)?
var key4: (() -> Void)?
private lazy var buttonTitles = [
["1", "2", "3"],
["4", "5", "6"],
["7", "8", "9"]
]
override func viewDidLoad() {
super.viewDidLoad()
setupKeyboard()
}
lazy var mainStackView: UIStackView = {
let mainStackView = UIStackView()
mainStackView.axis = .vertical
mainStackView.distribution = .fillEqually
mainStackView.spacing = 16
mainStackView.translatesAutoresizingMaskIntoConstraints = false
return mainStackView
}()
private func setupKeyboard() {
let keyboardView = UIView(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 279.0))
keyboardView.addSubview(mainStackView)
NSLayoutConstraint.activate([
mainStackView.topAnchor.constraint(equalTo: keyboardView.topAnchor, constant: 16),
mainStackView.leadingAnchor.constraint(equalTo: keyboardView.leadingAnchor, constant: 0),
mainStackView.trailingAnchor.constraint(equalTo: keyboardView.trailingAnchor, constant: -24),
mainStackView.bottomAnchor.constraint(equalTo: keyboardView.bottomAnchor, constant: -35)
])
// Create rows
for (_, _) in buttonTitles.enumerated() {
let rowStackView = UIStackView()
rowStackView.axis = .horizontal
rowStackView.distribution = .fillEqually
rowStackView.spacing = 1
// Create buttons for each row
for title in rowTitles {
let button = createButton(title: title)
rowStackView.addArrangedSubview(button)
}
mainStackView.addArrangedSubview(rowStackView)
}
self.view = keyboardView
}
private func createButton(title: String) -> UIButton {
switch title {
///returns a uibutton based on title
}
}
// MARK: - Button Actions
@objc private func numberTapped(_ sender: UIButton) {
if let number = sender.title(for: .normal) {
key1?(number)
}
}
@objc private func key2Called() {
key2?()
}
@objc private func key3Called() {
key3?()
}
@objc private func key4Called() {
key4?()
}
deinit {
// Clear any strong references
key1 = nil
key2 = nil
key3 = nil
key4 = nil
for subview in mainStackView.arrangedSubviews {
if let stackView = subview as? UIStackView {
for button in stackView.arrangedSubviews {
(button as? UIButton)?.removeTarget(self, action: nil, for: .allEvents)
}
}
}
mainStackView.removeFromSuperview()
}
}
Environment
iOS 16.3
Xcode 18.3.1
Any insights would be greatly appreciated as this is causing noticeable memory growth in my app over time.
Explore the various UI frameworks available for building app interfaces. Discuss the use cases for different frameworks, share best practices, and get help with specific framework-related questions.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Here’s a clearer and more concise version of your question:
I’m creating an AppIntent to allow users to log their body weight. My intent includes a @Parameter defined as:
@Parameter(
title: "Weight",
description: "Current Weight",
defaultUnit: .pounds,
supportsNegativeNumbers: false
)
var weight: Measurement<UnitMass>
This works but doesn’t respect the user’s Locale and its measurementSystem. When I add defaultUnitAdjustForLocale: true to the @Parameter macro, the default always switches to kilograms, regardless of the locale.
How can I correctly set the default unit to match the user’s locale for the purpose of entering a users body weight?
Getting this error in iPhone Portrait Mode with notch.
Currrently using AVQueuePlayer to play more than 30 mp3 files one by one.
All constraint properties are correct but error occures only in Apple iPhone Portrait Mode with notch series. But same code works on same iPhone in Landscape mode.
**But I get this error: **
LoudnessManager.mm:709 unable to open stream for LoudnessManager plist
Type: Error | Timestamp: 2025-02-07 | Process: | Library: AudioToolbox | Subsystem: com.apple.coreaudio | Category: aqme | TID: 0x42754
LoudnessManager.mm:709 unable to open stream for LoudnessManager plist
LoudnessManager.mm:709 unable to open stream for LoudnessManager plist
Timestamp: 2025-02-07 | Library: AudioToolbox | Subsystem: com.apple.coreaudio | Category: aqme
I tried to use AppIntentConfiguration in iOS17 to fail to achieve such a dynamic configuration.
code:
struct ConfigurationAppIntent: WidgetConfigurationIntent {
static var title: LocalizedStringResource { "位置" }
static var description: IntentDescription { "选择位置以展示城市天气" }
@Parameter(title: "Select City", optionsProvider: CityOptionsProvider())
var selectedCity: String?
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
I am developing an application which make use of 2 ornaments anchored to a volumetric window, one used a toolbar and one to display different views.
The problem I am facing consistently is that the ornaments seems to scale up or down after moving the volume using the OS handle or starting a GroupActivity session.
This first image shows the ornaments as soon as I started the app, no dragging nor group activities:
This second images shows them as soon as I join a group activity session:
The map, which might seem smaller, has not been touched and has always the same scale.
In this last image I had just dragged the entire volume using the OS toolbar, resulting in the ornaments scaling down:
This is how the volume and the ornaments are declared:
WindowGroup(id: "CityVolume") {
let cityVM = CityViewModel(volumeSize: CityView.initialVolumeSize)
CityView(cityVM: cityVM)
.ornament(attachmentAnchor: .scene(.bottomFront)) {
HStack {
TourismChartsButton()
LandmarksListButton()
CenterMapButton()
ToggleImmersiveSpaceButton()
TrafficDataButton()
BusLinesButton()
}
.padding()
.offset(z: 10)
.rotation3DEffect(Angle(degrees: 15), axis: (x: 1.0, y: 0.0, z: 0.0))
}
.ornament(attachmentAnchor: .scene(.back)) {
ZStack {
if AppModel.Instance.tourismVM.isChartViewVisible {
TourismChartsView()
}
if AppModel.Instance.busLinesVM.isDataViewEnabled {
BusLineView()
}
}
}
.task(observeGroupActivity)
.onAppear {
appModel.cityVM = cityVM
}
}
.windowStyle(.volumetric)
.windowResizability(.contentSize)
.volumeWorldAlignment(.gravityAligned)
.defaultSize(CityView.initialVolumeSize, in: .meters)
It happens also without starting a SharePlay session, but not as frequently as during SharePlay. Experienced the same behaviour with toolbars.
Am I doing something wrong with how I created the ornaments? Am I missing something?
I have an app on the Mac App Store (so sandboxed) that includes a QuickLook Preview Extension that targets Markdown files. It established a QLPreviewingController instance for the macOS QuickLook system to access and it works.
I'm in the process of updating it so that it displays inline images referenced in the file as well as styling the file's text. However, despite setting Downloads folder read-only access permission (and user-selected, though I know that shouldn't be required: no open/save dialogs here) in the extension's entitlements, Sandbox refuses too allow access to the test image: I always get a deny(1) file-read-data error in the log.
FWIW, the test file is referenced in the source Markdown as an absolute unix file path.
I've tried different signings and no joy. I’ve tried placing the referenced image in various other locations. Also no joy. All I can display is the error-case bundle image for 'missing image'.
Question is, is this simply something that QuickLook extensions cannot do from within the sandbox, or am I missing something? Is there anything extra I can do to debug this?
Description
When using UIDocumentPickerViewController with allowsMultipleSelection = false, I expect that selecting a file will dismiss only the document picker.
However, if a user quickly taps the same file multiple times, the picker dismisses both itself and the presenting view controller (i.e., it pops two levels from the view controller stack), which leads to unintended behavior and breaks presentation flow.
Expected Behavior
Only UIDocumentPickerViewController should be dismissed when a file is selected—even if the user taps quickly or multiple times on the same file.
Actual Behavior
When tapping the same file multiple times quickly, the picker dismisses not only itself but also the parent view controller it was presented from.
Steps to Reproduce
Create a simple view controller and present another one modally over it.
From that presented view controller, present a UIDocumentPickerViewController with allowsMultipleSelection = false.
Tap quickly on the same file in the picker 2 times.
Result: Both the document picker and the presenting view controller are dismissed.
Reproducible Code Snippet
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .green
addLabel("Parent View Controller")
DispatchQueue.main.async { [unowned self] in
let child = UIViewController()
child.view.backgroundColor = .yellow
present(child, animated: true)
child.addLabel("Child View Controller")
let vc = UIDocumentPickerViewController(
forOpeningContentTypes: [.pdf, .jpeg, .png],
asCopy: true
)
vc.allowsMultipleSelection = false
child.present(vc, animated: true)
}
}
}
extension UIViewController {
func addLabel(_ text: String) {
let label = UILabel(frame: CGRect(x: 0, y: 50, width: view.bounds.width, height: 30))
label.text = text
view.addSubview(label)
}
}
Environment
Device: iPhone 15 Pro and others
iOS version: 18.2 (reproduces on multiple iOS versions)
Occurs with: .pdf, .jpeg, .png file types
Mode: Both simulator and real device
Notes
Happens consistently with fast multiple taps on the same file.
This breaks expected view controller stack behavior.
I am facing same issue with major crash while coming out from this function.
Basically using collectionView.dequeReusableCell with size calculation.
func getSizeOfFavouriteCell(_ collectionView: UICollectionView, at indexPath: IndexPath, item: FindCircleInfoCellItem) -> CGSize { guard let dummyCell = collectionView.dequeueReusableCell( withReuseIdentifier: TAButtonAddCollectionViewCell.reuseIdentifier, for: indexPath) as? TAButtonAddCollectionViewCell else { return CGSize.zero }
dummyCell.title = item.title
dummyCell.subtitle = item.subtitle
dummyCell.icon = item.icon
dummyCell.layoutIfNeeded()
var targetSize = CGSize.zero
if viewModel.favoritesDataSource.isEmpty.not,
viewModel.favoritesDataSource.count > FindSheetViewControllerConstants.minimumFavoritesToDisplayInSection {
targetSize = CGSize(width: collectionView.frame.size.width / 2, height: collectionView.frame.height)
var estimatedSize: CGSize = dummyCell.systemLayoutSizeFitting(targetSize)
if estimatedSize.width > targetSize.width {
estimatedSize.width = targetSize.width
}
return CGSize(width: estimatedSize.width, height: targetSize.height)
}
}
We have resolve issue with size calculation with checking nil. Working fine in xcode 15 and 16+.
Note: Please help me with reason of crash? Is it because of xCode 16.2 onwards **strict check on UICollectionView **
There has been a long lasting UIStackView bug dating back to 2016 that still exists in the latest Xcode 16.3 and SDKs, where calling setHidden:true multiple times (lets say twice) on a subview of that stack view requires calling setHidden:false twice before the subview shows up again.
This was originally documented via Radar #25087688.
Hopefully a Frameworks Engineer here on the forums can raise it to the attention of the appropriate engineers. It would be really nice if this eventually gets fixed, because it's one of those odd issues where you end up wasting a lot of time trying to debug because everything looks correct.
I want record screen in my app,the method startCaptureWithHandler:completionHandler:,the sampleBuffer, It is supposed to exist but it has become nil.Not only that,but there‘s another problem,when I want to stop recording and save the video,I will check [RPScreenRecorder sharedRecorder].recording first, it will be false sometime,that problems are unusual in iOS 18.3.2 iPhoneXs Max,and unexpected,here is my code
-(void)startCaptureScreen {
NSLog(@"AKA++ startCaptureScreen");
if ([[RPScreenRecorder sharedRecorder] isRecording]) {
return;
}
//屏幕录制
[[RPScreenRecorder sharedRecorder]setMicrophoneEnabled:YES];
NSLog(@"AKA++ MicrophoneEnabled AAAA startCaptureScreen");
[[RPScreenRecorder sharedRecorder]setCameraEnabled:YES];
[[RPScreenRecorder sharedRecorder] startCaptureWithHandler:^(CMSampleBufferRef _Nonnull sampleBuffer, RPSampleBufferType bufferType, NSError * _Nullable error) {
if(self.assetWriter == nil){
if (self.AVAssetWriterStatus == 0) {
[self setupAssetWriterAndStartWith:sampleBuffer];
}
}
if (self.AVAssetWriterStatus != 2) {
return;
}
if (error) {
// deal with error
return;
}
if (self.assetWriter.status != AVAssetWriterStatusWriting) {
[self assetWriterAppendSampleBufferFailWith:bufferType];
return;
}
if (bufferType == RPSampleBufferTypeVideo) {
if(self.assetWriter.status == 0 ||self.assetWriter.status > 2){
} else if(self.videoAssetWriterInput.readyForMoreMediaData == YES){
BOOL success = [self.videoAssetWriterInput appendSampleBuffer:sampleBuffer];
}
}
if (bufferType == RPSampleBufferTypeAudioMic) {
if(self.assetWriter.status == 0 ||self.assetWriter.status > 2){
} else if(self.audioAssetWriterInput.readyForMoreMediaData == YES){
BOOL success = [self.audioAssetWriterInput appendSampleBuffer:sampleBuffer];
}
}
} completionHandler:^(NSError * _Nullable error) {
//deal with error
}];
}
and than ,when want to save it :
-(void)stopRecording {
if([[RPScreenRecorder sharedRecorder] isRecording]){
// The problem is sporadic,recording action failed,it makes me confused
}
[[RPScreenRecorder sharedRecorder] stopCaptureWithHandler:^(NSError * _Nullable error) {
if(!error) {
//post message
}
}];
}
Title:
SIGTRAP Crash in QuartzCore/CALayer during UI Lifecycle Changes
Description:
My app is experiencing occasional crashes triggered by a SIGTRAP signal during UI transitions (e.g., scene lifecycle changes, animations). The crash occurs in QuartzCore/UIKitCore code paths, and no business logic appears in the stack trace.
Crash Context:
Crash occurs sporadically during UI state changes (e.g., app backgrounding, view transitions).
Stack trace involves pthread_mutex_destroy, CA::Layer::commit_if_needed, and UIKit scene lifecycle methods.
Full crash log snippet:
Signal: SIGTRAP
Thread 0 Crashed:
0 libsystem_platform.dylib 0x... [symbol: _platform_memset$VARIANT$Haswell]
2 libsystem_pthread.dylib pthread_mutex_destroy + 64
3 QuartzCore CA::Layer::commit_if_needed(...)
4 UIKitCore UIScenePerformActionsWithLifecycleActionMask + 112
5 CoreFoundation _CFXNotificationPost + 736
Suspected Causes:
Threading Issue: Potential race condition in pthread_mutex destruction (e.g., mutex used after free).
UI Operation on Background Thread: CALayer/UIKit operations not confined to the main thread.
Lifecycle Mismatch: Scene/UI updates after deallocation (e.g., notifications triggering late UI changes).
Troubleshooting Attempted:
Enabled Zombie Objects – no obvious over-released objects detected.
Thread Sanitizer shows no clear data races.
Verified UIKit/CoreAnimation operations are dispatched to MainThread.
Request for Guidance:
Are there known issues with CA::Layer::commit_if_needed and scene lifecycle synchronization?
How to debug SIGTRAP in system frameworks when no app code is in the stack?
Recommended tools/approaches to isolate the mutex destruction issue.
I've been trying to add a header to the tabSection of the tabview in tvos 18+ .
init(
@TabContentBuilder<SelectionValue> content: () -> Content,
@ViewBuilder header: () -> Header
) where Header : View, Footer == EmptyView
Here the ehader clearly conforms to View but i cant quite fit the label with uiimage as the icon into this. This Label when i add it to any other view, the image is in the specified 50 x 50 size but inside header it functions weirdly to be of a huge size. but also to note, if i simply hav an icon here, it is correct. So what is the problem here.. can someone help me? im supposed to add the user profile and name in the header. I dont think there's any other way
As the title says, I am not sure how to properly build an inverted ScrollView where I can safely insert items above my data ("prepend") without everything jumping around.
My current code is essentially this:
@State private var scrollPosition = ScrollPosition(idType: Message.ID.self)
private func onMessageDidScrollIntoView(_ id: Message.ID) {
let indexOfVisibleMessage = /* ... */
if indexOfVisibleMessage < 10 {
fetchOlderMessages()
// ^ this updates my ViewModel `messages`
}
}
var body: some View {
ScrollView {
LazyVStack {
ForEach(messages) { message in
MessageCell(message)
}
}.scrollTargetLayout()
}
.defaultScrollAnchor(.bottom)
.scrollPosition($scrollPosition)
.onChange(of: scrollPosition) { oldValue, newValue in
guard let visibleMessageId = scrollPosition.viewID(type: Message.ID.self) else { return }
onMessageDidScrollIntoView(visibleMessageId)
}
}
..so if the user scrolls up to the oldest 10 messages, I start loading more and insert them at the top.
The problem with this is that the ScrollView now jumps when new messages are inserted. This is because the ScrollView maintains it's Y position, but the content size changes since we are adding new items "above".
I tried to play around with a few suggestions I found on StackOverflow, namely;
Inverting the ScrollView (.scaleEffect(y: -1) on the ScrollView and then again on the MessageCell to counter it): This somehow jumped the x position of the ScrollView and completely breaks .contextMenu.
Playing around with .onScrollGeometryChange to update scrollPosition.scrollTo(y:) when it's contentSize changes: This just didn't work and stopped the user scroll gesture/interaction.
Setting scrollPosition to the Message.ID I want to keep stable before doing an update: This didn't do anything.
But nothing actually worked for the reasons described above.
How do you actually build these UIs in SwiftUI? I think an inverted ScrollView is quite a common UI, and obviously data has to be loaded lazily.
I have an app which uses Scene
var body: some Scene {
WindowGroup {
RootView(root: appDelegate.root)
.edgesIgnoringSafeArea(.all)
.onOpenURL { url in
let stringUrl = url.absoluteString
if (stringUrl.starts(with: "http")) {
handleUniversalLink(url: stringUrl)
} else if (stringUrl.starts(with: "fb")) {
let _ = ApplicationDelegate.shared.application(
UIApplication.shared,
open: url,
sourceApplication: nil,
annotation: [UIApplication.OpenURLOptionsKey.annotation])
}
}
}
}
I need to detect when a user taps on status bar. And call some functions when he does it. Is it possible in Swift?
Topic:
UI Frameworks
SubTopic:
SwiftUI
I released an app for iPhone (and it's could be downloaded for iPad also), and now I developered another app for iPad version with the same code and logic but I modified the layout to fit bigger screen and make better user experience and appearance.
Howevert the app review rejected my release due to the duplicate content, how can I solve it?
Topic:
UI Frameworks
SubTopic:
General
My SwiftUI app uses an Image with a tap gesture:
Image(systemName: "xmark.circle.fill")
.accessibilityIdentifier(kTextFieldClearButton)
.foregroundColor(.secondary)
.padding(.trailing, 6)
.onTapGesture {
dataSource.textFieldText = ""
}
In a UI test, I want to tap this image to execute its action:
let clearButton = app.images[kTextFieldClearButton]
clearButton.tap()
However the action is not executed.
I then set a breakpoint at clearButton.tap(), to execute lldb commands. Here are the results:
(lldb) p clearButton.isHittable
t = 439.54s Find the "TextFieldClearButton" Imag
(Bool) true
e
It is a little strange that "Image" has been interrupted by (Bool) true, but the image is hittable.
p clearButton.isAccessibilityElement
gives
(lldb) p clearButton.isAccessibilityElement
(Bool) false
I don't understand why this Image is no accessibility element. I thought, SwiftUI Views are by default accessible.
What can I do to make it accessible so that clearButton.tap() works as expected?
I think it can be dismissed with dismiss() onInAppPurchaseCompletion action handler but I have no reason to handle it, and if it's not handled it will show error alerts for you (see documentation).
How can I dismiss it and still benefit from default onInAppPurchaseCompletion action?
Thanks,
I have a SwiftUI view of the form
struct ContentView: View {
// ...
.onDrop(of: [.pdf], isTargeted: $isDropTargeted) { pdfs in
for pdf in pdfs {
I'm just not sure what to do next, I see there's a loadPreviewImage() that if I use like:
Task.detached {
// returns any NSSecureCoding object
let image = try! await pdf.loadPreviewImage()
}
Not sure how I'm supposed to get my preview image from that NSSecureCoding object
Topic:
UI Frameworks
SubTopic:
SwiftUI
We were using below delegate methods from QuickLook to get modified PDF file URL after the sketching But we are not able see the multi line text properly laid out on PDF and part of text missing. Same time Other pencil kit tools are working as expected.
`func previewController(_ controller: QLPreviewController, didSaveEditedCopyOf previewItem: QLPreviewItem, at modifiedContentsURL: URL)
func previewController(_ controller: QLPreviewController, didUpdateContentsOf previewItem: any QLPreviewItem)`
We tested all code in iOS 18.2.
Please let us know if the text edited URL on PDF can be retrieved in any possible way without tampering text
We are developing an MacOS app from our iOS app using MacCatalyst.
If I press long on the app icon on the Dock, a list of recent files appears.
If I tap one one of these files nothing happens. I would expect the scene delegate function:
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>)
would be called but it is not. Can somebody maybe explain what I am missing here?
The list of recent files also appears in the Menu under File > Open recent files. There I can tap on a file and it it is opened correctly using the scene delegate method mentioned above.
The files can also be opened with the app using the Finder, so the associated file types with the app are correct.