When referencing WebKit’s function callAsyncJavaScript, any iOS app crashes immediately on startup when running in simulator. On device, it does not crash.
The error message is:
dyld[9892]: Symbol not found: _$sSo9WKWebViewC6WebKitE19callAsyncJavaScript_9arguments2inAF17completionHandlerySS_SDySSypGSo11WKFrameInfoCSgSo14WKContentWorldCys6ResultOyyps5Error_pGcSgtF
Furthermore, this only happens for some simulators.
With Xcode 16.3, it’s simulators 18.0 and prior.
With Xcode 16.4 RC1 it includes simulators iOS 18.5 and 18.4 but works correctly on earlier versions of simulator.
The reproduction path is easy. Example file attached.
This used to work about 3 weeks or a month ago, which is perplexing.
As a workaround I replaced the function with evaluateJavaScript which does not crash, but that is not the desired method to use for us.
The attached file can reproduce it easily - just refernece this view from the default ContentView in a new project.
TestWebView.swift
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'm running into an issue while developing an iOS app that requires local network access. I’m using the latest MacBook Air M4 with macOS sequoia 15.5 and Xcode 16.1. In the iOS Simulator, my app fails to discover devices connected to the same local network.
I’ve already added the necessary key to the Info.plist:
NSLocalNetworkUsageDescription
This app needs access to local network devices.
When I run the app on a real device and M2 Chip Macbook's simulators, it works fine for local network permission as expected. However, in the M4 Chip Macbook's Simulator:
The app can’t find any devices on the local network
Bonjour/mDNS seems not to be working as well
I’ve tried the following without success:
Restarting Simulator and Mac
Resetting network settings in Simulator
Confirming app permissions under System Settings > Privacy & Security
Has anyone else encountered this issue with the new Xcode/macOS combo? Is local network access just broken in the Simulator for now, or is there a workaround?
Thanks in advance!
Greetings
I'm trying to get on iPad the SSID from the wifi I'm connected to. For that, I added the wifi entitlement and I'm requesting permission to the user for Location.
Once I have it, I'm using the function CNCopySupportedInterfaces to get the interfaces, but I can only receive the en0, which using the method CNCopyCurrentNetworkInfo returns nil.
I also tried using the NEHotspotNetwork.fetchCurrent and the SSID keeps being nil. So right now I'm drawing a blank. Is there any way to make it work? Thanks.
Topic:
App & System Services
SubTopic:
Networking
Tags:
Swift
Network Extension
Network
Core Location
I'm developing an iPadOS 18+ application that uses a UITabBarController, styled as a sidebar, to serve as the primary navigation interface. This setup includes 20 different tabs, each representing a distinct section of the app.
For the user experience, each tab needs to present a master-detail interface, implemented using a UISplitViewController. The goal is to allow users to navigate between tabs via the sidebar, and within each tab, access related content through the split view's list-detail pattern.
The Problem:
Currently, my implementation involves instantiating a separate UISplitViewController for each tab, resulting in 20 unique split view instances embedded inside the UITabBarController. While this works functionally, it leads to significant memory usage, especially after the user opens each tab at least once. The accumulation of all these instantiated view controllers in memory eventually causes performance degradation or even memory warnings/crashes on lower-end iPads.
The Question:
What is the best approach to implement this type of architecture without running into memory management issues?
Specifically:
Is there a way to reuse or lazily load the UISplitViewController instances only when needed?
Can we unload or release split view controllers that haven't been used for a while to reduce memory pressure?
Would a custom container controller be more appropriate than using UITabBarController in this case?
Are there iPadOS 18+ best practices or newer APIs that support this kind of complex multi-tab, multi-split-view structure efficiently?
Any advice on how to optimize memory usage while preserving the sidebar navigation and split view layout would be highly appreciated.
Hello,
We have a SwiftUI-based application that runs as a LaunchAgent and communicates with other internal components using Unix domain sockets (UDS).
On Sequoia (macOS virtualized environment), when installing the app, we encounter the Local Network Privacy Alert, asking:
"Allow [AppName] to find and connect to devices on the local network?"
We are not using any actual network communication — only interprocess communication via UDS.
Is there a way to prevent this system prompt, either through MDM configuration or by adjusting our socket-related implementation?
Here's a brief look at our Swift/NIO usage:
class ClientHandler: ChannelInboundHandler {
...
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
...
}
...
}
// init bootstrap.
var bootstrap: ClientBootstrap {
return ClientBootstrap(group: group)
// Also tried to remove the .so_reuseaddr, the prompt was still there.
.channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.channelInitializer { channel in
// Add ChannelInboundHandler reader.
channel.pipeline.addHandler(ClientHandler())
}
}
// connect to the UDS.
self.bootstrap.connect(unixDomainSocketPath: self.path).whenSuccess { (channel) in
..
self.channel = channel
}
...
...
// Send some data.
self.channel?.writeAndFlush(buffer).wait()
Any guidance would be greatly appreciated.
Hi!
I'm working on a web extension for Safari and I need to send messages from the containing application to JavaScript. For this I use the method
class func dispatchMessage(
withName messageName: String,
toExtensionWithIdentifier identifier: String,
userInfo: [String : Any]? = nil
) async throws
of the SFSafariApplication class. If the site is opened in Safari in normal mode, everything works as expected. However, if the site is "docked", the messages are not transmitted to this "Web App".
Is it possible to somehow link the container application to the docked website so that messages from the application are received by this "Web App"?
That you.
I'm facing a bizarre issue with the Apple's Accessibility APIs. I am registering an AXObserver that listens for, among other things, the kAXSelectedTextChangedNotification. For many new users, the kAXSelectTextChangedNotification is not triggered, even though they have enabled Accessibility permission for the app. Other notifications are getting through (kAXWindowMovedNotification, kAXWindowResizedNotification, kAXValueChangedNotification etc - full list here), just not the kAXSelectedTextChangedNotification!
We've found that we can reproduce the error by removing accessibility permission for the app and rebooting our computers. After restarting and reenabling accessibility permissions, the kAXSelectedTextChangedNotification was not received, even though other notifications were fine.
Strangely, the issue can be resolved by launching Apple's Accessibility Inspector app on an impacted computer. Once the Accessibility Inspector is loaded, the kAXSelectedTextChangedNotifications start coming through as expected. This implies to me that either:
We are missing some needed setup when starting the observers. Accessibility Inspector gets it right, thus ‘starting’ the system properly.
Accessibility Inspector is using some Apple private APIs that we don’t have access to.
Things I’ve tried:
I've tried subscribing the AXSelectedTextChangedNotification to different AXUIElements, including the SystemWide element, the Application element, and children elements from the AXApplication. None of these received the kAXSelectedTextChangedNotification, until Accessibility Inspector is booted up. No surprises here, as Apple's documentation confirms that you should add the notification to the root Application AXUIElement if you want to receive notifications for all its children.
I had a theory that the issue might be due to my code calling AXUIElementCreateApplication multiple times, possibly creating multiple "Applications" in Apple's Accessibility implementation. If that’s the case, the notifications might be sent to the wrong application AXUIElement. However, refactoring my code to only call AXUIElementCreateApplication once didn't resolve the issue.
I thought the issue may be caused by subscribing the AXSelectedTextChangedNotification on the high-level application element (at odds with Apple's documentation). I've tried traversing the child AXUIElements until we find one with the kAXSelectedTextAttribute and then subscribing to that. This did not resolve the issue. I don’t think it's the correct path to continue exploring, given that the notifications are received correctly after AccessibilityInspector is launched.
There is one exception to the above: if I add the kSelectedTextChangedNotification listener to a specific text field AXUIElement, I do receive the notification on that text field. However, this is not practical; I need a solution that will work for all text fields within an app. The Accessibility Inspector appears to be doing something that causes the selected-text-changed notifications to be correctly passed up to the high-level application AXUIElement.
Another thought is that I could traverse the entire Accessibility hierarchy and add listeners to every subview that has the kAXSelectedTextAttribute. However, I don’t like this long-term solution. It will be slow and incomplete: new elements get added and removed frequently. I just want the kAXSelectedTextChangedNotification to be received by the high-level Application AXUIElement, which the documentation suggests it should be. I also have evidence that this can work, since notifications start coming through after Accessibility Inspector is launched. It’s just a matter of discovering how to replicate whatever Accessibility Inspector is doing.
An interesting wrinkle: I implemented the 'traverse' strategy above, but was surprised by how few elements were in the hierarchy. Most apps only go down ~2-3 levels, which didn't seem right to me. Perhaps the Accessibility tree isn't fully initialized? I tried adding a 5-second delay to allow more initialization time, but it didn't change anything.
Does anyone have any ideas? Here's our file.
For many years I've had the following code to access the active objects of a table view in my App Store app:
class MyViewController: NSViewController: NSMenuItemValidation {
private var tableView: NSTableView!
private var objects = [MyObject]()
func numberOfRows(in tableView: NSTableView) -> Int {
return objects.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
// make view for row
}
private var activeObjects: [MyObject] {
return tableView?.activeRowIndexes.map({ objects[$0] }) ?? []
}
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
let activeObjects = self.activeObjects
...
}
}
extension NSTableView {
var activeRowIndexes: IndexSet {
return clickedRow == -1 || selectedRowIndexes.contains(clickedRow) ? selectedRowIndexes : IndexSet(integer: clickedRow)
}
}
In one of the recent updates, I wanted to add some kind of header to the table view, so I decided to add a row at the beginning and offset the indexes by 1.
func numberOfRows(in tableView: NSTableView) -> Int {
return objects.count + 1
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
if row == 0 {
// make header view
} else {
// make view for row - 1
}
}
private var activeObjects: [MyObject] {
return tableView?.activeRowIndexes.subtracting(IndexSet(integer: 0)).map({ objects[$0 - 1] }) ?? []
}
But since I added this change, Xcode regularly downloads crash reports from clients crashing during menu item validation in IndexSet.map with reason Code 5 Trace/BPT trap: 5. I assumed that I was accessing an invalid array index, so I added some debug code: the crash report would then show the invalid index beside the crashed thread's name.
private var activeObjects: [MyObject] {
return tableView?.activeRowIndexes.subtracting(IndexSet(integer: 0)).map({ i in
if !objects.indices.contains(i - 1) {
Thread.current.name = (Thread.current.name ?? "") + ". Invalid index \(i - 1) for count \(objects.count)"
preconditionFailure()
}
return objects[i - 1]
}) ?? []
}
But the crash reports for this new app version look just like the old ones and the thread name is not changed. Indeed, when recreating an invalid index access on my Mac, the crash report mentions Array._checkSubscript(_:wasNativeTypeChecked:), which does not appear in the crash reports downloaded by Xcode.
Manually symbolicating the crash report also doesn't give any more information: all lines referring to my app code are resolved to either /<compiler-generated>:0 or MyViewController.swift:0.
Apparently the problem is not an invalid array index, but something else. Does anybody have a clue what the problem could be?
(Note: the crash report mentions Sequence.compactMap because now I'm effectively calling tableView?.activeRowIndexes.compactMap, but the same crash happened before when calling IndexSet.map, which would appear in the crash report as Collection.map.)
crash2.crash
I have a button with the following properties:
accessibilityLabel: "Action Button",
traits: "Button",
accessibilityHint: "Performs the main action".
The voiceover reads the button as follows:
Action Button, Button, Performs the main action.
I want to understand how to configure it to only speak the accessibilityHint or only the accessibilityLabel and never speak the traits.
In another example, a switch has the traits: Button, and Toggle. So these traits are a part of what the voiceover speaks. I want only the accessibilityLabel or accessibilityHint to be spoken in this case.
Please let me know how.
Thanks
I am trying to do inline to icon and text in tab bar but it is not allowing me to do it in compact, but it showing me in regular mode , but in regular mode tab bar going at top in portrait mode , But my requirement is tab bar required in bottom with icon and text in inline it showed by horizontally but it showing to me stacked vertically, will you guide me on this so that I can push the build to live users.
Hello,
I tried to use the ManagedAppView component to display a list of apps, I have a text field above my list to make it searchable.
The problem is that when the keyboard appear, all my ManagedAppView components shift half of their height up, inside there list cell, so they are only half visible with the rest of the cell blank.
As the component is Apple Internal, I didn't find any solution to avoid that, is there any fix to have this component stays in place even when the keyboard appear ?
I tried to replace the ManagedAppView by other components and the issue arise only with ManagedAppView.
I am aware the USB / HID devices can come and go, if you have a long running application that's what you want to monitor.
But for a "one-shot" command-line tool for example, I would like to enumerate the devices present on a system at a certain point in time, interact with a subset of them (and this interaction can fail since the device may have been disconnected in-between enumerating and me creating the HIDDeviceClient), and then exit the application.
It seems that HIDDeviceManager only allows monitoring an Async[Throwing]Stream which provides the initial devices matching the query but then continues to deliver updates, and I have no idea when this initial list is done.
I could sleep for a while and then cancel the stream and see what was received up to then, but that seems like the wrong way to go about this, if I just want to know "which devices are connected", so I can maybe list them in a "usage" or help screen.
Am I missing something?
Hi Community,
I'm new on Siri intents and I'm trying to introduce into my App a Siri Intent for Car Commands. The objective is to list into the Apple Maps the Car list of my App. Currently I've created my own target with its corresponding IntentHandlings, but in the .intentdefinition file of my App, I'm not able to find the List Car Intent.
https://developer.apple.com/documentation/sirikit/car-commands
Do I need some auth?
Also I share my info.plist from the IntentExtension.
Thank you very much,
David.
Topic:
App & System Services
SubTopic:
Automation & Scripting
Tags:
Swift
SiriKit
Intents
App Intents
Its document says openDocument can open a document at a specific URL. So I've saved a model as a JSON object with its URL and a bookmark as Data. With its security-scoped bookmark data resolved, I am able to open a document except that the app will crash right after opening a document. Console says
should only be called in the main thread
struct ContentView: View {
@EnvironmentObject var bookmarkViewModel: BookmarkViewModel
var body: some View {
VStack {
}
.onAppear {
loadBookmarks()
}
}
extension ContentView {
func loadBookmarks() {
print("1 \(Thread.current)") // NSMainThread
Task {
for bookmarkItem in bookmarkViewModel.bookmarkItems { // resolving a security-scoped bookmark
print("2 \(Thread.current)") // NSMainThread
if let _ = resolveBookmark(bookmarkData: bookmarkItem.bookmarkData) {
print("3 \(Thread.current)") // NSMainThread
do {
print("4 \(Thread.current)") // NSMainThread
try await openDocument(at: bookmarkItem.bookmarkURL)
print("5 \(Thread.current)") // NSMainThread
} catch {
print("\(error.localizedDescription)")
}
}
}
}
}
}
Well, the application is on the main thread. I've checked every line before and after opening a document with its URL. Call what on the main thread? This is confusing. Thanks.
class BookmarkViewModel: ObservableObject {
@Published var bookmarkItems: [BookmarkItem] = []
var defaultFileManager: FileManager {
return FileManager.default
}
var documentURL: URL? {
...
}
init() {
fetchBookmarkItems()
}
func fetchBookmarkItems() {
bookmarkItems.removeAll()
if let documentURL {
let bookmarkFolderURL = documentURL.appending(path: "MyApp").appending(path: "Bookmarks")
do {
let contents = try defaultFileManager.contentsOfDirectory(atPath: bookmarkFolderURL.path)
for content in contents {
...
let fileURL = bookmarkFolderURL.appending(path: content)
let data = try Data(contentsOf: fileURL)
let bookmarkItem = try JSONDecoder().decode(BookmarkItem.self, from: data)
bookmarkItems.append(bookmarkItem)
}
} catch {
print("Error fetching folder content: \(error.localizedDescription)")
}
}
}
}
struct BookmarkItem: Codable, Hashable {
let bookmarkURL: URL
let date: Date
let bookmarkData: Data
let open: Bool
}
Hoping someone can help me with this…
The error is… Generic parameter ‘/‘ cannot be inferred.
.multilineTextAlignment(.center)
.onAppear(perform: {
var checkFirstCardLatitude = cards.firstCardLatitude
let charArray = Array(checkFirstCardLatitude)
let allowed: [Character] = ["-", ".", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
for char in charArray {
if char != allowed {
cards.firstCardLatitude = "000.000000" // Reset Text Field
}
}
})
How can you force cancel a task that doesn't need cleanup and doesn't check for cancellation?
If this cannot be done, would this be a useful addition to Swift?
Here is the situation:
The async method doesn't check for cancellation since it is not doing anything repetively (for example in a loop). For example, the method may be doing "try JSONDecoder().decode(Dictionary<String, ...>.self, from: data)" where data is a large amount.
The method doesn't need cleanup.
I would like the force cancellation to throw an error. I am already handling errors for the async method.
My intended situation if that the user request the async method to get some JSON encoded data, but since it is taking longer that they are willing to wait, they would tap a cancellation button that the app provides.
I can't find a viable path to call StoreKit from C++ right now and would love some ideas.
I'm implementing the code exactly as shown at 4:09 in
https://developer.apple.com/videos/play/wwdc2023/10172/
However when I add any StoreKit functionality in I immediately get
"Actor isolated structure cannot be exposed in C++"
This makes me think I can't create a StoreKit view and call it from C++? Am I missing a better way? I don't think I can have another structure that holds the storeChooser in it because it will have the same problem (I assume, although I will check). Part of the issue seems to be that my app is C++ so there is no main function called in the swift for me to open this view with either, I was going to use the present function Zoe described (as below).
I've tried a lot of alternative approaches but it seems to be blocking async functions from showing in C++ as well. So I'm not sure how to access the basic product(for:) and purchase(product) functions.
import Foundation
import StoreKit
import SwiftUI
public struct storeChooser: View {
public var productIDs: [String]
public var fetchError: String
//@State //Note this is from the UI
@State public var products: [Product] = []
// @State private var isPresented = true
// weak private var host: UIViewController? = nil
public init() {
productIDs = ["20_super_crystals_v1"]
products = []
self.fetchError = "untried"
}
public var body: some View {
VStack(spacing: 20) {
Text( "Products")
ForEach(self.products) { product in
Button {
//dont do anything yet
} label: {
Text("\(product.displayPrice) - \(product.displayName)")
}
}
}.task {
do {
try await self.loadProducts()
} catch {
print(error)
}
}
}
public func queryProducts() {
Task {
do {
try await self.loadProducts()
} catch {
print(error)
}
}
}
public func getProduct1Name() -> String {
if self.products.count > 0 {
return self.products[0].displayName
} else {
return "empty"
}
}
private func loadProducts() async throws {
self.products = try await Product.products(for: self.productIDs)
}
/* public mutating func present(_ viewController: UIViewController) {
isPresented = true;
let host = UIHostingController(rootView: self)
host.rootView.host = host
viewController.present(host, animated: true)
} */
}
What is the most obvious method of calling StoreKit from C++. I'm getting blocked by the fact that most of the critical StoreKit calls are async and functions marked a sync don't show up in the swift header for me to call from C++ (at least as far as I can tell).
I'm trying to call
let result = try await Product.products(for:productIDs) or
let result = try await product.purchase()
And C++ can't even see any functions I wrap these in as far as I can tell because i have to make them async. What am I missing?
I tried a lot of alternates, like wrapping in
Task { let result = try await Product.products(for:productIDs) }
and it gives me 'Passing closure as a sending parameter' errors.
Also when I try to call the same above code it gives me 'initializtion of immutable value never used' errors and the variables never appear.
Code:
struct storeChooser {
public var productIDs: [String]
public function checkProduct1 {
Task { let result = try await Product.products(for: productIDs) }
The above gives the initialization of immutable value skipped, and when I create a
@State var products
Then I get the 'passing closure as a sending parameter' error when i try to run it in a task
it appears if I could make the function async and call it from C++ and have it return nothing it may work, does anyone know how to get C++ to see an async function in the -Swift.h file?
Hello,
I'm encountering a runtime crash when building my visionOS app with Xcode 16.3 for visionOS 2.5. Our existing AppStore/Testflight app is also instantly crashing on visionOS 2.5 when opened but works fine on e.g visionOS 2.4.
The app builds successfully but crashes on launch with this symbol lookup error (slightly adjusted because the forum complained regarding sensitive data):
Symbol not found: _$sSo22CLLocationCoordinate2DVSE12CoreLocationMc
Referenced from: <XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX> /private/var/containers/Bundle/Application/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/MyApp.app/MyApp.debug.dylib
Expected in: <XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX> /usr/lib/swift/libswiftCoreLocation.dylib
dyld config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/usr/lib/libLogRedirect.dylib:/usr/lib/libBacktraceRecording.dylib:/usr/lib/libMainThreadChecker.dylib:/System/Library/PrivateFrameworks/GPUToolsCapture.framework/GPUToolsCapture:/usr/lib/libViewDebuggerSupport.dylib
I've already implemented my own Codable conformance for CLLocationCoordinate2D:
extension CLLocationCoordinate2D: Codable {
// implementation details...
}
This worked fine on previous visionOS/Xcode versions. Has anyone encountered this issue or found a solution?
System details:
macOS version: 15.3.2
Xcode version: 16.3
visionOS target: 2.5
Thank you!
After two types of objects correctly inserted as nodes in an augmented reality setting, I replicated exactly the same procedure with a third kind of objects that unfortunately refuse to show up. I checked the flow and it is the same as the other objects as well the content of the LocationAnnotation, but there is surely something that escapes me. Could someone help with some ideas?
This is the common code, apart of the class:
func appendInAR(ghostElement: Ghost){
let ghostElementAnnotationLocation=GhostLocationAnnotationNode(ghost: ghostElement)
ghostElementAnnotationLocation.scaleRelativeToDistance = true
sceneLocationView.addLocationNodeWithConfirmedLocation(locationNode: ghostElementAnnotationLocation)
shownGhostsAnnotations.append(ghostElementAnnotationLocation)
}