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.
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
and yeah, swift vaguely is reminiscent of a programming language I developed, but
I want swift To do
return if (var blah:Int32 == 43){
blah = blah2;
}
your welcome !! thank me on my new accounting job lol =/
basically I want to return conditional statements for a private reason
Consider this stripped-down example of a view with a view model:
import Observation
import SwiftUI
struct MainView: View {
@State private var viewModel = ViewModel()
private let items = [0, 1, 2]
var body: some View {
List {
GroupedItemsView(
viewModel : viewModel.groupState,
groupedItems : [(0, items)]
)
}
}
}
fileprivate struct GroupedItemsView<ViewModel: GroupsExpandable>: View {
let viewModel : ViewModel
let groupedItems : [(ViewModel.GroupTag, [Int])]
var body: some View {
ForEach(groupedItems, id: \.0) { groupTag, items in
Text("nothing")
}
}
}
fileprivate protocol GroupsExpandable: AnyObject { // HERE
associatedtype GroupTag: Hashable
}
fileprivate final class GroupState<GroupTag: Hashable>: GroupsExpandable {}
@Observable
fileprivate final class ViewModel {
var groupState = GroupState<Int>()
}
#Preview {
MainView()
}
This compiles and runs fine in the Simulator, but it crashes in the Preview.
However, when I remove the fileprivate modifier before GroupsExpandable (see HERE), it also runs in the Preview.
What is the reason for this? Bug in Preview? Error on my side somewhere?
Thanks.
System is Xcode Version 16.3 (16E140) on a MacBook Pro 2018 (Intel) running Sequoia 15.3.2
Devices are iPhone 16 Pro Max with iOS 18.3.1, compiler is set to Swift 6.
Version: iOS 18.1 and later (works as expected on iOS 18.0 and earlier)
Area: SpringBoard / Notification Center / App Icon Rendering
Description: When changing the app's alternate icon using UIApplication.setAlternateIconName(_:completionHandler:), the icon is updated correctly on the Home Screen and App Switcher. However, in Notification Center, the old app icon is still shown for notifications, even after the change has completed. This issue only occurs on iOS 18.1 and later. In iOS 18.0 and earlier, Notification Center correctly reflects the updated icon.
- Steps to reproduce:
Create an iOS app with alternate app icons configured in the Info.plist.
Use UIApplication.shared.setAlternateIconName("IconName") to change the icon at runtime.
Send a notification.
Pull down Notification Center and observe the icon shown beside the notification.
- Expected Behavior:
Notification Center should reflect the updated (alternate) app icon immediately after the change.
- Actual Behavior:
Notification Center continues to display the old (primary) app icon. The new icon appears correctly on the Home Screen and App Switcher. Restarting the device does cause Notification Center to update and reflect the correct icon, which suggests a cache or refresh issue in SpringBoard or Notification Center.
- Notes:
Issue introduced in iOS 18.1; not present in 18.0.
Reproduces on both physical devices and simulators.
Occurs with both scheduled local notifications and remote notifications.
Restarting the device updates the Notification Center icon, but this is not a viable user-facing workaround.
Topic:
App & System Services
SubTopic:
Notifications
Tags:
Swift
APNS
User Notifications
Notification Center
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 **
How can I return the results of a Spotlight query synchronously from a Swift function?
I want to return a [String] that contains the items that match the query, one item per array element.
I specifically want to find all data for Spotlight items in the /Applications folder that have a kMDItemAppStoreAdamID (if there is a better predicate than kMDItemAppStoreAdamID > 0, please let me know).
The following should be the correct query:
let query = NSMetadataQuery()
query.predicate = NSPredicate(format: "kMDItemAppStoreAdamID > 0")
query.searchScopes = ["/Applications"]
I would like to do this for code that can run on macOS 10.13+, which precludes using Swift Concurrency. My project already uses the latest PromiseKit, so I assume that the solution should use that. A bonus solution using Swift Concurrency wouldn't hurt as I will probably switch over sometime in the future, but won't be able to switch soon.
I have written code that can retrieve the Spotlight data as the [String], but I don't know how to return it synchronously from a function; whatever I tried, the query hangs, presumably because I've called various run loop functions at the wrong places.
In case it matters, the app is a macOS command-line app using Swift 5.7 & Swift Argument Parser 1.5.0. The Spotlight data will be output only as text to stdout & stderr, not to any Apple UI elements.
Environment→ ・Device: iPad 10th generation ・OS:**iOS18.3.2
I'm using AVAudioSession to record sound in my application. But I recently came to realize that when the app starts a recording session on a tablet, OS automatically sets the tablet volume to 50% and when after recording ends, it doesn't change back to the previous volume level before starting the recording. So I would like to know whether this is an OS default behavior or a bug?
If it's a default behavior, I much appreciate if I can get a link to the documentation.
Hello,
I am developing an application which is communicating with external device using BLE and L2CAP. I wonder what are the best practices of using Input & Output streams that are established with L2CAP connection when working with Swift 6 concurrency model.
I've been trying to find some examples and hints for some time now but unfortunately there isn't much available. One useful thread I've found is: https://developer.apple.com/forums/thread/756281
but it does not offer much insight into using eg. actor model with streams. I wonder if something has changed in this regards?
Also, are there any plans to migrate eg. CoreBluetooth stack to new swift 6 concurrency ?
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
External Accessory
Swift
Core Bluetooth
Concurrency
Hi Apple Developer Community,
I'm facing a crash when updating an array of tuples from both a background thread and the main thread simultaneously. Here's a simplified version of the code in a macOS app using AppKit:
class ViewController: NSViewController {
var mainthreadButton = NSButton(title: "test", target: self, action: nil)
var numbers = Array(repeating: (dim: Int, key: String)(0, "default"), count: 1000)
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(mainthreadButton)
mainthreadButton.translatesAutoresizingMaskIntoConstraints = false
mainthreadButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
mainthreadButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
mainthreadButton.widthAnchor.constraint(equalToConstant: 100).isActive = true
mainthreadButton.heightAnchor.constraint(equalToConstant: 100).isActive = true
mainthreadButton.target = self
mainthreadButton.action = #selector(arraytest(_:))
}
@objc func arraytest(_ sender: NSButton) {
print("array update started")
// Background update
DispatchQueue.global().async {
for i in 0..<1000 {
self.numbers[i].dim = i
}
}
// Main thread update
var sum = 0
for i in 0..<1000 {
numbers[i].dim = i + 1
sum += numbers[i].dim
print("test \(sum)")
}
mainthreadButton.title = "test = \(sum)"
}
}
This results in a crash with the following message:
malloc: double free for ptr 0x136040c00
malloc: *** set a breakpoint in malloc_error_break to debug
What's interesting:
This crash only happens when the tuple contains a String ((dim: Int, key: String))
If I change the tuple type to use two Int values ((dim: Int, key: Int)), the crash does not occur
My Questions:
Why does mutating an array of tuples containing a String crash when accessed from multiple threads?
Why is the crash avoided when the tuple contains only primitive types like Int?
Is there an underlying memory management issue with value types containing reference types like String?
Any explanation about this behavior and best practices for thread-safe mutation of such arrays would be much appreciated.
Thanks in advance!
I get many warnings like this when I build an old project.
I asked AI chatbot which gave me several solutions, the recommended one is:
var hashBag = [String: Int]()
func updateHashBag() async {
var tempHashBag = hashBag // make copy
await withTaskGroup(of: Void.self) { group in
group.addTask {
tempHashBag["key1"] = 1
}
group.addTask {
tempHashBag["key2"] = 2
}
}
hashBag = tempHashBag // copy back?
}
My understanding is that in the task group, the concurrency engine ensures synchronized modifications on the temp copy in multiple tasks. I should not worry about this.
My question is about performance.
What if I want to put a lot of data into the bag? Does the compiler do some kind of magics to optimize low level memory allocations? For example, the temp copy actually is not a real copy, it is a special reference to the original hash bag; it is only grammar glue that I am modifying the copy.
There's an easily reproducible SwiftUI bug on macOS where an app's UI state no longer updates/re-renders for "Designed for iPad" apps (i.e. ProcessInfo.processInfo.isiOSAppOnMac == true). The bug occurs in Xcode and also if the app is running independent of Xcode.
The bug occurs when:
the user Hides the app (i.e. it goes into the background)
the user puts the Mac to sleep (e.g. Apple menu > Sleep)
a total of ~60 seconds transpires (i.e. macOS puts the app into the "suspended state")
when the app is brought back into the foreground the UI no longer updates properly
The only way I have found to fix this is to manually open a new actual full app window via File > New, in which case the app works fine again in the new window.
The following extremely simple code in a default Xcode project illustrates the issue:
import SwiftUI
@main
struct staleApp: App {
@State private var isBright = true
var body: some Scene {
WindowGroup() {
ZStack {
(isBright ? Color.white : Color.black).ignoresSafeArea()
Button("TOGGLE") { isBright.toggle(); print("TAPPED") }
}
.onAppear { print("\(isBright ? "light" : "dark") view appeared") }
}
}
}
For the code above, after Hiding the app and putting the computer to sleep for 60 seconds or more, the button no longer swaps views, although the print statements still appear in the console upon tapping the button. Also, while in this buggy state, i can get the view to update to the current state (i.e. the view triggered by the last tap) by manually dragging the corner of the app window to resize the window. But after resizing, the view again does not update upon button tapping until I resize the window again.
so it appears the diff engine is mucked or that the Scene or WindowGroup are no longer correctly running on the main thread
I have tried rebuilding the entire view hierarchy by updating .id() on views but this approach does NOT work. I have tried many other options/hacks but have not been able to reset the 'view engine' other than opening a new window manually or by using: @Environment(.openWindow) private var openWindow
openWindow could be a viable solution except there's no way to programmatically close the old window for isiOSAppOnMac (@Environment(.dismissWindow) private var dismissWindow doesn't work for iOS)
I am developing iOS App using SwiftUI and I notice that Myanmar font of number text on 18.4 have clipped on top and bottom. Does anyone have this issues and know the fix? I have provided the Screenshot also.
when i set the flag false to the usesClassicLoadingMode, then the application is getting crashed
Ex:
let config = URLSessionConfiguration.default
if #available(iOS 18.4, *) {
config.usesClassicLoadingMode = false
}
Crash log :
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFBoolean objectForKeyedSubscript:]: unrecognized selector sent to instance 0x1f655c390' *** First throw call stack: (0x188ae52ec 0x185f69a7c 0x188b4f67c 0x1889fcb84 0x1889fc4f0 0x191393bc8 0x1889ec8a0 0x1889ec6e4 0x191393ad0 0x191344dac 0x191344b58 0x107cfa064 0x107ce36d0 0x191343fcc 0x1891b3b18 0x1892dae58 0x189235c60 0x18921e270 0x18921d77c 0x18921a8ac 0x107ce0584 0x107cfa064 0x107ce891c 0x107ce95d8 0x107ceabcc 0x107cf5894 0x107cf4eb0 0x212f51660 0x212f4e9f8) terminating due to uncaught exception of type NSException
Hi, upgraded to Xcode Version 16.3 (16E140) today and now Playground can't execute JSON decoding. The code below is taken from Apple's own JSONDecoder example:
struct GroceryProduct: Codable {
var name: String
var points: Int
var description: String?
}
let json = """
{
"name": "Durian",
"points": 600,
"description": "A fruit with a distinctive scent."
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
let product = try decoder.decode(GroceryProduct.self, from: json)
print(product.name) // Prints "Durian"
This use to work in the previous Xcode version. Now I get this error:
The LLDB RPC server has crashed. The crash log is located in ~/Library/Logs/DiagnosticReports and has a prefix 'lldb-rpc-server'.
This file doesn't exist in the location. I've restarted Xcode and the Mac, same error.
Any thoughts?
To get menubar size, we can call.
let menuBarHeight = NSStatusBar.system.thickness
That is returning 24 and it is the same as my external screen. I did command + shift + 5 and use the screen capture tool to rougly measure the size of menubar. It is roughly 24px.
However, for my macbook pro 14 inches m2 pro. The menubar seem thicker because of the webcam. Is there a way to find out the size in Swift?
When i try to set the value ‘false’ for ‘usesClassicLoadingMode’ it is getting crashed.
The crash logs has been shared below
Ex:
let config = URLSessionConfiguration.default
if #available(iOS 18.4, *) {
config.usesClassicLoadingMode = false
}
Error log :
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFBoolean objectForKeyedSubscript:]: unrecognized selector sent to instance 0x1f655c390'
*** First throw call stack:
(0x188ae52ec 0x185f69a7c 0x188b4f67c 0x1889fcb84 0x1889fc4f0 0x191393bc8 0x1889ec8a0 0x1889ec6e4 0x191393ad0 0x191344dac 0x191344b58 0x107cfa064 0x107ce36d0 0x191343fcc 0x1891b3b18 0x1892dae58 0x189235c60 0x18921e270 0x18921d77c 0x18921a8ac 0x107ce0584 0x107cfa064 0x107ce891c 0x107ce95d8 0x107ceabcc 0x107cf5894 0x107cf4eb0 0x212f51660 0x212f4e9f8)
terminating due to uncaught exception of type NSException
Can you please provider the resolution steps
I tried to build the project with Xcode 16.3 and I initially got an error that TARGET_IPHONE_SIMULATOR does not exist, then I changed this flag to TARGET_OS_SIMULATOR, but it did not solve the problem
In the attached code snippet:
struct ContentView: View {
@State private var vText: String = ""
var body: some View {
TextField("Enter text", text: Binding(
get: { vText },
set: { newValue in
print("Text will change to: \(newValue)")
vText = newValue
}
))
}
}
I have access to the newValue of the text-field whenever the text-field content changes, but how do I detect which key was pressed? I can manually get the diff between previous state and the new value to get the last pressed char but is there a simpler way? Also this approach won't let me detect any modifier keys (such as Alt, Ctrl etc) that the user may have pressed.
Is there a pure swift-ui approach to detect these key presses?
I have a macro that converts expression into a string literal, e.g.:
#toString(variable) -> "variable"
#toString(TypeName) -> "TypeName"
#toString(\TypeName.property) -> "property"
In Xcode 16.3 #toString(TypeName) stopped to work, compilation throws 'Expected member name or initializer call after type name' error.
Everything works fine in Xcode 16.2. I tried to compare build settings between 16.2 and 16.3 but haven't noticed differences that may cause this new error.
The following works in both Xcode versions:
#toString(variable) -> "variable"
#toString(\TypeName.property) -> "property"
Seems like Xcode tries to compile code that shouldn't be compiled because of macro expansion.
Does anybody know what new has appeared in 16.3 and, perhaps, how to fix the problem?
Dare anyone try the following code in any Playground:
// Define a model that conforms to Codable
struct User: Codable {
var name: String
var age: Int
var email: String?
}
// JSON data (as a string for demonstration)
let jsonString = """
{
"name": "John Doe",
"age": 30,
"email": "john@example.com"
}
"""
// Convert the JSON string to Data
if let jsonData = jsonString.data(using: .utf8) {
do {
// Parse the JSON data into the User model
let user = try JSONDecoder().decode(User.self, from: jsonData)
print("Name: \(user.name), Age: \(user.age), Email: \(user.email ?? "N/A")")
} catch {
print("Error decoding JSON: \(error)")
}
}
I tested with Xcode 16.2 and latest 16.3, it reliably crashes the lldb server!