Swift 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

ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS
Is this possible while inserting a String into Set Crashed: com.apple.root.user-initiated-qos.cooperative 0 libswiftCore.dylib 0xf4c0 _assertionFailure(_:_:flags:) + 136 1 libswiftCore.dylib 0x17f484 ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS(_:) + 3792 2 MyEatApp 0x44f6e8 specialized _NativeSet.insertNew(_:at:isUnique:) + 4333926120 (<compiler-generated>:4333926120) 3 MyEatApp 0x44eaec specialized Set._Variant.insert(_:) + 4333923052 (<compiler-generated>:4333923052) 4 MyEatApp 0x479f7c HomeViewModel.hanldeAnnouncementCard(from:) + 293 (HomeViewModel+PersonalizedOffer.swift:293) 5 libswift_Concurrency.dylib 0x5c134 swift::runJobInEstablishedExecutorContext(swift::Job*) + 292 6 libswift_Concurrency.dylib 0x5d5c8 swift_job_runImpl(swift::Job*, swift::SerialExecutorRef) + 156 7 libdispatch.dylib 0x13db0 _dispatch_root_queue_drain + 364 8 libdispatch.dylib 0x1454c _dispatch_worker_thread2 + 156 9 libsystem_pthread.dylib 0x9d0 _pthread_wqthread + 232 10 libsystem_pthread.dylib 0xaac start_wqthread + 8
6
0
286
2w
Is my POST method correct
//Is my post method correct because google and claude are telling me I must use content type for the json and use .setvalue. I thought that my process was correct because I encode the data to turn into json and then make the request func createTask(_ task: Task) async throws -> Task { if let url = URL(string: "(baseURL)/todos"){ var request = URLRequest(url: url) request.httpMethod = "POST" let encoder = JSONEncoder() do{ let data = try encoder.encode(task) request.httpBody = data let (data, response) = try await URLSession.shared.data(for: request) return task //we want to make encoder and then turn the data into json and put it in body } catch{ throw JSONErrors.encodingFailed } } else{ throw URLError(.badURL) } }
Topic: Safari & Web SubTopic: General Tags:
2
0
108
2w
ZoneSharing CloudKit UI
I am trying to use Zone Sharing in my SwiftUI app. I have been attempting to get the UICloudSharingController to show an initial share screen to pick users and the mechanism to send the invitation. From the documentation, it appears that the UICloudSharingController .init(preparationHandler:) API is deprecated so I am not using that approach. Following the Apple documentation, I am creating a Zone Share and NOT saving it and presenting using the UICloudSharingController(share:container:) API. However, this presents a UI that is the 'mgmt' API for a Share. I can get to the UI I was expecting by tapping on the 'Share with More People' option, but I want to start on that screen for the user when they have not shared this before. So, I found an example app from Apple at: https://github.com/apple/sample-cloudkit-zonesharing. It has the same behavior. So we can simply discuss this problem based on that example code. How do I get the next View presented when tapping 'Share Group' to be the invitation for new users screen? Here is the UI it presents initially: And here is the UI (on the bottom half of the screen) I am trying to start the share process with: Thanks, Charlie
3
0
80
1w
What is the best way to retrieve data from a server
Hello, I am new to App development, so I am looking for some advice. I want to develop an app for iPhone, which downloads files (pdf, jpg)from a server to the local storage. I also want to get data from the server to be used in my app. This could be a database access or just simple xml files. I want a secure access based on userid and password. Since in a later version, my app should also run on Android Phones, I am reluctant to use iCloud. I was thinking sftp, but that does not seem to be supported for iOS.
4
0
52
2w
Tab bar controller drag and drop order of items not working
Hi I'm using Xcode 16.4 on a Mac mini m4 so please let's not get in the weeds about latest this or that for software, etc... I'm trying to move one of the tab bar items in the controller, the home item, the the far left and I can grab it and drag it but it won't drop anywhere except where it exists. the other items won't move either. I've googled this and not finding anything stating you have to do a key combo, etc... which I've tried the command, option and control keys each with the dragging. Also the ability to actually select and item to drag it is extremely inconsistent, sometimes it grabs it and most of the time it doesn't. do I need to just delete the connectors and add them back in the proper order? is that really the solution here?
3
0
78
3d
@State variable returns empty despite being set in .onAppear function
With the code below, JSON data is parsed and is stored in the variable data in the .onAppear function, however an empty set of data is passed to the Content view. How can that be fixed so that the JSON data passes to the DataView? struct ContentView: View { @State var data: [Data] @State var index: Int = 0 var body: some View { VStack { DataView(data: data[index]) } .onAppear { let filePath = Bundle.main.path(forResource: "data", ofType: "json") let url = URL(fileURLWithPath: filePath!) data = getData(url: url) } } func getData(url: URL) -> [Data] { do { let data = try Data(contentsOf: url) let jsonDecoded = try JSONDecoder().decode([Data].self, from: data) return jsonDecoded } catch let error as NSError { print("Fail: \(error.localizedDescription)") } catch { print("Fail: \(error)") } return [] } }
17
1
448
3w
Crash in Swift 6 when using UNUserNotification
After porting code to Swift 6 (Xcode 16.4), I get a consistent crash (on simulator) when using UNUserNotificationServiceConnection It seems (searching on the web) that others have met the same issue. Is it a known Swift6 bug ? Or am I misusing UNUserNotification ? I do not have the crash when compiling on Xcode 26 ß5, which hints at an issue in Xcode 16.4. Crash log: Thread 10 Queue : com.apple.usernotifications.UNUserNotificationServiceConnection.call-out (serial) As far as I can tell, it seems error is when calling nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) I had to declare non isolated to solve a compiler error. Main actor-isolated instance method 'userNotificationCenter(_:didReceive:withCompletionHandler:)' cannot be used to satisfy nonisolated requirement from protocol 'UNUserNotificationCenterDelegate' I was advised to: Add 'nonisolated' to 'userNotificationCenter(_:didReceive:withCompletionHandler:)' to make this instance method not isolated to the actor I filed a bug report: Aug 10, 2025 at 2:43 PM – FB19519575
4
0
119
3w
Swift 6 conversion for IBOutlet
I'm struggling to convert Swift 5 to Swift 6. As advised in doc, I first turned strict concurrency ON. I got no error. Then, selected swift6… and problems pop up. I have a UIViewController with IBOutlets: eg a TextField. computed var eg duree func using UNNotification: func userNotificationCenter I get the following error in the declaration line of the func userNotificationCenter: Main actor-isolated instance method 'userNotificationCenter(_:didReceive:withCompletionHandler:)' cannot be used to satisfy nonisolated requirement from protocol 'UNUserNotificationCenterDelegate' So, I declared the func as non isolated. This func calls another func func2, which I had also to declare non isolated. Then I get error on the computed var used in func2 Main actor-isolated property 'duree' can not be referenced from a nonisolated context So I declared duree as nonsilated(unsafe). Now comes the tricky part. The computed var references the IBOutlet dureeField if dureeField.text == "X" leading to the error Main actor-isolated property 'dureeField' can not be referenced from a nonisolated context So I finally declared the class as mainActor and the textField as nonisolated @IBOutlet nonisolated(unsafe) weak var dureeField : UITextField! That silences the error (but declaring unsafe means I get no extra robustness with swift6) just to create a new one when calling dureeField.text: Main actor-isolated property 'text' can not be referenced from a nonisolated context Question: how to address properties inside IBOutlets ? I do not see how to declare them non isolated and having to do it on each property of each IBOutlet would be impracticable. The following did work, but will make code very verbose: if MainActor.assumeIsolated({dureeField.text == "X"}) { So I must be missing something.
5
0
593
3w
Swift 6 Minimum Requirement for App Store
Good afternoon, all! I was wondering if there was a timeline for when the App Store and/or TestFlight will drop support for Swift 5? I know Swift 6 was released last year and historically App Store requires a certain SDK minimum for upload. I was wondering if any SDK update was on the docket that would effectively force applications onto Swift 6? Looking at past releases, I had estimated mid to late 2026, but I wanted to confirm? Swift 4 Released September 2017 Became the default SDK in Xcode 9 Strongly "encouraged" via the iOS 12 SDK in late 2018 Essentially "required" by early 2019 Swift 5 Released March 2019 Became the default SDK in Xcode 10.2 Strongly "encouraged" via the iOS 12.1 SDK in early 2019 Essentially "required" by late 2020 Swift 6 Released June 2024 Became the default SDK in Xcode 16 Strongly "encouraged" via the iOS 18 SDK in April 2025 **Essentially "required" by mide-late 2026 ?? ** Thank you in advance!
4
0
122
3w
Issue with beta Declared Age Range
I'm trying to work with the beta version of the Declared Age Range framework based on an article's tutorial but am getting the following error: [C:1-3] Error received: Invalidated by remote connection. and AgeRangeService.Error.notAvailable is being thrown on the call to requestAgeRange. I'm using Xcode 26 beta 5 and my simulator is running the 26.0 beta. The iCloud account that I have signed into the simulator has a DOB set as well. This is my full ContentView where I'm trying to accomplish this. struct ContentView: View { @Environment(\.requestAgeRange) var requestAgeRange @State var advancedFeaturesEnabled = false var body: some View { VStack { Button("Advanced Features") {} .disabled(!advancedFeaturesEnabled) } .task { await requestAgeRangeHelper() } } func requestAgeRangeHelper() async { do { let ageRangeResponse = try await requestAgeRange(ageGates: 16) switch ageRangeResponse { case let .sharing(range): if let lowerBound = range.lowerBound, lowerBound >= 16 { advancedFeaturesEnabled = true } case .declinedSharing: break // Handle declined sharing default: break } } catch AgeRangeService.Error.invalidRequest { print("Invalid request") // Handle invalid request (e.g., age range < 2 years) } catch AgeRangeService.Error.notAvailable { print("Not available") // Handle device configuration issues } catch { print("Other") } } }
1
0
85
Aug ’25
Compile Failure on NSXPCInterface Initializer
I have a project that leverages XPC and has interoperability between Swift and Objective-C++. I am presently getting a compile-time error in one of our unit test targets, of "Argument passed to call that takes no arguments" on the following code: let interface = NSXPCInterface(with: XPCServiceDelegate.self) My XPCServiceDelegate protocol is defined as: @objc(XPCServiceDelegate) public protocol XPCServiceDelegate { //... } For the longest time, this code has compiled successfully, and it has not recently changed. There are two confusing things about this error. The first is that I have a different build scheme that will compile correctly other code with the same structure. The other is that I have team members that are able to compile my failing scheme successfully on the same XCode version, OSVersion, and branch of our repository. I've attempted numerous things to try to get this code to compile, but I've run out of ideas. Here's what I've tried: Clean build both on XCode 16.4 and XCode 26 Beta Delete DerivedData and rebuild on XCode 16.4 and XCode 26 Beta Delete and re-clone our git repository Uninstall and reinstall XCode Attempt to locate cached data for XCode and clear it out. (I'm not sure if I got everything that exists on the system for this.) Ensure all OS and XCode updates have been applied. The interface specification for NSXPCInterface clearly has an initializer with one arguement for the delegate protocol, so I don't know why the compiler would fail for this. Is there some kind of forward declaration or shadowing of NSXPCInterface? Do you have any ideas on what I could try next?
10
0
120
3w
Using Dynamic Member Lookup in a Superclass
As a fun project, I'm wanting to model an electronic circuit. Components inherit from a superclass (ElectronicComponent). Each subclass (e.g. Resistor) has certain methods to return properties (e.g. resistance), but may vary by the number of outlets (leads) they have, and what they are named. Each outlet connects to a Junction. In my code to assemble a circuit, while I'm able to manually hook up the outlets to the junctions, I'd like to be able to use code similar to the following… class Lead: Hashable // implementation omitted { let id = UUID() unowned let component: ElectronicComponent weak var connection: Junction? init(component: ElectronicComponent, to connection: Junction? = nil) { self.component = component self.connection = connection } } @dynamicMemberLookup class ElectronicComponent { let id = UUID() var connections: Set<Lead> = [] let label: String? init(label: String) { self.label = label } subscript<T>(dynamicMember keyPath: KeyPath<ElectronicComponent, T>) -> T { self[keyPath: keyPath] } func connect(lead: KeyPath<ElectronicComponent, Lead>, to junction: Junction) { let lead = self[keyPath: lead] lead.connection = junction connections.insert(lead) } } class Resistor: ElectronicComponent { var input, output: Lead? let resistance: Measurement<UnitElectricResistance> init(_ label: String, resistance: Measurement<UnitElectricResistance>) { self.resistance = resistance super.init(label: label) } } let resistorA = Resistor("R1", resistance: .init(value: 100, unit: .ohms)) let junctionA = Junction(name: "A") resistorA.connect(lead: \.outlet2, to: junctionA) While I'm able to do this by implementing @dynamicMemberLookup in each subclass, I'd like to be able to do this in the superclass to save repeating the code. subscript<T>(dynamicMember keyPath: KeyPath<ElectronicComponent, T>) -> T { self[keyPath: keyPath] } Unfortunately, the compiler is not allowing me to do this as the superclass doesn't know about the subclass properties, and at the call site, the subclass isn't seen as ElectronicComponent. I've been doing trial and error with protocol conformance and other things, but hitting walls each time. One possibility is replacing the set of outlets with a dictionary, and using Strings instead of key paths, but would prefer not to. Another thing I haven't tried is creating and adopting a protocol with the method implemented in there. Another considered approach is using macros in the subclasses, but I'd like to see if there is a possibility of achieving the goal using my current approach, for learning as much as anything.
6
0
337
Aug ’25
How to fix the gestureRecognizer over PDFKit breaking the paging in the new ios26 version?
I had project going great, where i needed to do stuff with pdfs, drawing on top them etc. Since apple is all closed sourced i needed to become a bit hacky. Anyways, i have a problem since the new ios 26 update which breaks the behaviour. I simplified the code very much into a demo project, where you can quickly see what's wrong. When swiping left to go to the next page, it does change the page etc in the pdf Document, but visually nothing happens. I am stuck on the first page. I dont know what to do, tried a lot of things, but nothing works. Anyone skilled enough to help me out? import UIKit import PDFKit import SwiftUI class PDFViewController: UIViewController { var pdfView: PDFView! var gestureHandler: GestureHandler! override func viewDidLoad() { super.viewDidLoad() setupPDFView() setupGestureHandler() loadPDF() } private func setupPDFView() { pdfView = PDFView(frame: view.bounds) // Your exact configuration pdfView.autoScales = true pdfView.pageShadowsEnabled = false pdfView.backgroundColor = .white pdfView.displayMode = .singlePage view.addSubview(pdfView) // Setup constraints pdfView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ pdfView.topAnchor.constraint(equalTo: view.topAnchor), pdfView.leadingAnchor.constraint(equalTo: view.leadingAnchor), pdfView.trailingAnchor.constraint(equalTo: view.trailingAnchor), pdfView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) } private func setupGestureHandler() { gestureHandler = GestureHandler(pdfView: pdfView) gestureHandler.setupSwipeGestures(on: view) } private func loadPDF() { if let path = Bundle.main.path(forResource: "sonate12", ofType: "pdf"), let document = PDFDocument(url: URL(fileURLWithPath: path)) { pdfView.document = document } else { print("Could not find sonate12.pdf in bundle") } } } class GestureHandler { private weak var pdfView: PDFView? init(pdfView: PDFView) { self.pdfView = pdfView } func setupSwipeGestures(on view: UIView) { // Left swipe - go to next page let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:))) leftSwipe.direction = .left view.addGestureRecognizer(leftSwipe) // Right swipe - go to previous page let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:))) rightSwipe.direction = .right view.addGestureRecognizer(rightSwipe) } @objc private func handleSwipe(_ gesture: UISwipeGestureRecognizer) { guard let pdfView = pdfView, let document = pdfView.document, let currentPage = pdfView.currentPage else { print("🚫 No PDF view, document, or current page available") return } let currentIndex = document.index(for: currentPage) let totalPages = document.pageCount print("📄 Current state: Page \(currentIndex + 1) of \(totalPages)") print("👆 Swipe direction: \(gesture.direction == .left ? "LEFT (next)" : "RIGHT (previous)")") switch gesture.direction { case .left: // Next page guard currentIndex < document.pageCount - 1 else { print("🚫 Already on last page (\(currentIndex + 1)), cannot go forward") return } let nextPage = document.page(at: currentIndex + 1) if let page = nextPage { print("➡️ Going to page \(currentIndex + 2)") pdfView.go(to: page) pdfView.setNeedsDisplay() pdfView.layoutIfNeeded() // Check if navigation actually worked DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { if let newCurrentPage = pdfView.currentPage { let newIndex = document.index(for: newCurrentPage) print("✅ Navigation result: Now on page \(newIndex + 1)") if newIndex == currentIndex { print("⚠️ WARNING: Page didn't change visually!") } } } } else { print("🚫 Could not get next page object") } case .right: // Previous page guard currentIndex > 0 else { print("🚫 Already on first page (1), cannot go back") return } let previousPage = document.page(at: currentIndex - 1) if let page = previousPage { print("⬅️ Going to page \(currentIndex)") pdfView.go(to: page) pdfView.setNeedsDisplay() pdfView.layoutIfNeeded() let bounds = pdfView.bounds pdfView.bounds = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.width + 0.01, height: bounds.height) pdfView.bounds = bounds // Check if navigation actually worked DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { if let newCurrentPage = pdfView.currentPage { let newIndex = document.index(for: newCurrentPage) print("✅ Navigation result: Now on page \(newIndex + 1)") if newIndex == currentIndex { print("⚠️ WARNING: Page didn't change visually!") } } } } else { print("🚫 Could not get previous page object") } default: print("🤷‍♂️ Unknown swipe direction") break } } } struct PDFViewerRepresentable: UIViewControllerRepresentable { func makeUIViewController(context: Context) -> PDFViewController { return PDFViewController() } func updateUIViewController(_ uiViewController: PDFViewController, context: Context) { // No updates needed } } You can look at the code here as well: https://github.com/vallezw/swift-bug-ios26
0
1
121
Aug ’25
Playground Macro Raises Error when compiled with Swift 6
In my Xcode app, I was attempting to use the #Playground macro to play around with some of the Foundation Model features to see if they would work for my iOS app. However, every time I used a #Playground macro, even if it was empty, it would receive the following error: /var/folders/q2/x5b9x0y161bb2l_0yj1_j6wm0000gn/T/swift-generated-sources/@__swiftmacro_20PlaygroundMacroIssue0022ContentViewswift_tiAIefMX26_0_33_B691877350F20F2DFC040B9E585F4D10Ll0A0fMf_.swift:51:5 Main actor-isolated let '$s20PlaygroundMacroIssue0022ContentViewswift_tiAIefMX26_0_33_B691877350F20F2DFC040B9E585F4D10Ll0A0fMf_23PlaygroundContentRecordfMu_' can not be referenced from a nonisolated context Here are my Xcode and system versions: Mac is running the first public beta of Tahoe. iOS Simulator is running 26.0 dev beta 4. Xcode is Xcode 26 beta 4. So, I went to try to reproduce the error in a blank iOS app project (the error above is the one that I reproduced in that project). Here are the steps that I took. I created a new iOS project in Xcode 26. I went into the ContentView.swift that was created for me and imported the Playgrounds module and created a blank #Playground at the bottom of the file. I then compiled the project and it ran just fine. To try to find out what the issue was, I looked at the concurrency settings. In my real app, Strict Concurrency Checking was set to Complete but was Minimal in my test project. So I went and changed that setting in my real app and it didn't fix anything. Next, I looked at the Swift Version, which turned out to be the culprit. My test app was running Swift 5 whereas the real app was running Swift 6. It seems to have crashed while running Swift 6, not 5. I have trouble understanding what the error is saying. I have tried using the Code Intelligence feature to fix the bug but it hasn't helped. Has anyone here experienced a similar bug? Is there something I can do to fix it or is this an error in Xcode that should be reported? I have attached an iCloud link to my test project if anybody wants to see if they can reproduce the issue: here Thanks!
2
0
90
Aug ’25
How to speed-up initial UI rendering faster in AppKit?
I am developing an AppKit application in MacOS with Swift. Our application requires a complex, multi-windowed interface and must deliver a very fast, responsive experience. As a performance test, I built a sample app that creates 3 windows programmatically, each containing 500 NSTextFields (with each text-field assigned 35 different properties). Code flow: https://gist.github.com/Raunit-TW/5ac58ac9c6584f93e2ee201aa8118139 This takes around 77 milliseconds to render the windows - I need to find a way to reduce this time, as low as possible. Thanks.
3
0
117
Aug ’25
Hide search field always
Greetings, Please type slowly, I'm new at this. iOS 18.x. Added search to a list, visibility toggled with a toolbar button, using this line of code: .searchable(text: $searchText, isPresented: $isSearchPresented, placement: .navigationBarDrawer(displayMode: .automatic), prompt: "Search...") Realized I was re-stating defaults, changed it to this: .searchable(text: $searchText, isPresented: $isSearchPresented, prompt: "Search...") In both cases, it works great when in the middle of the list, just like I wanted. However, when I scroll to the top of the list, the serach field is displayed even when 'isPresented' is false. Is there any way to keep the search field hidden even at the top of the list? ..thanks!
Topic: UI Frameworks SubTopic: SwiftUI Tags:
2
0
99
3w
how to use a 3D short cut with the totally closed application
I'm soliciting you because I'm having a problem using the 3D short cut for my ios application in uikit in the AppDelegate file but it's impossible to redirect the route when the user has completely killed the application. It works as a background application. I'd like it to redirect to the searchPage search page when the application is fully closed and the user clicks on search with 3D touch. final class AppDelegate: UIResponder, UIApplicationDelegate { lazy var window: UIWindow? = { return UIWindow(frame: UIScreen.main.bounds) }() private let appDependencyContainer = Container() private let disposeBag = DisposeBag() var pendingDeeplink: String? private lazy var onboardingNavigationController: UINavigationController = { let navigationController = UINavigationController(nibName: nil, bundle: nil) navigationController.setNavigationBarHidden(true, animated: false) return navigationController }() private func handleShortcutItem(_ shortcutItem: UIApplicationShortcutItem) { guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene, let window = windowScene.windows.first(where: { $0.isKeyWindow }), let rootVC = window.rootViewController else { DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in self?.handleShortcutItem(shortcutItem) } return } if let presentedVC = rootVC.presentedViewController { presentedVC.dismiss(animated: !UIAccessibility.isReduceMotionEnabled) { [weak self] in self?.executeShortcutNavigation(shortcutItem) } } else { executeShortcutNavigation(shortcutItem) } } private func executeShortcutNavigation(_ shortcutItem: UIApplicationShortcutItem) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in guard let self = self else { return } switch shortcutItem.type { case ShortcutType.searchAction.rawValue: self.mainRouter.drive(to: .searchPage(.show), origin: AppRoutingOrigin()) case ShortcutType.playAction.rawValue: self.mainRouter.drive(to: .live(channel: Channel(), appTabOrigin: AppTabOrigin.navigation.rawValue), origin: AppRoutingOrigin()) case ShortcutType.myListHistoryAction.rawValue: self.mainRouter.drive(to: .myList(.history), origin: AppRoutingOrigin()) default: break } } } What I've tried: Adding delays with DispatchQueue.main.asyncAfter Checking for window availability and rootViewController Dismissing presented view controllers before navigation Environment: iOS 15+ Swift 6 Using custom router system (mainRouter) App supports both SwiftUI and UIKit Questions: What's the best practice for handling shortcuts on cold launch vs warm launch? How can I ensure the router is properly initialized before navigation?
0
0
67
Jul ’25
Crash in WKScriptMessageHandler — CFRelease / CoreFoundation on iOS with WKWebView
We are building a hybrid iOS app using Angular (web) rendered inside a WKWebView, hosted by a native Swift app. Communication between the Angular UI and native Swift code is done using WKScriptMessageHandler. The app mostly works without issues, but in rare edge cases, we’re seeing crashes on the main thread, and the crash is reported in Firebase Crashlytics. The root cause appears related to CFRelease and WKScriptMessageHandler. Here’s the relevant crash stack: Crashed: com.apple.main-thread 0 CoreFoundation 0xbfac CFRelease + 44 1 CoreFoundation 0xa734 __CFURLDeallocate + 128 2 CoreFoundation 0x730c _CFRelease + 292 3 libobjc.A.dylib 0x4e28 AutoreleasePoolPage::releaseUntil(objc_object**) + 204 4 libobjc.A.dylib 0x4cbc objc_autoreleasePoolPop + 260 5 WebKit 0x99f194 WebKit::WebUserContentControllerProxy::didPostMessage(WTF::ObjectIdentifierGeneric<WebKit::WebPageProxyIdentifierType, WTF::ObjectIdentifierMainThreadAccessTraits<unsigned long long>, unsigned long long>, WebKit::FrameInfoData&&, WTF::ObjectIdentifierGeneric<WebKit::ScriptMessageHandlerIdentifierType, WTF::ObjectIdentifierMainThreadAccessTraits<unsigned long long>, unsigned long long>, std::__1::span<unsigned char const, 18446744073709551615ul>, WTF::CompletionHandler<void (std::__1::span<unsigned char const, 18446744073709551615ul>, WTF::String const&)>&&) + 680 6 WebKit 0x1b358 WebKit::WebUserContentControllerProxy::didReceiveMessage(IPC::Connection&, IPC::Decoder&) + 392 7 WebKit 0xe86b0 IPC::MessageReceiverMap::dispatchMessage(IPC::Connection&, IPC::Decoder&) + 272 8 WebKit 0x23c0c WebKit::WebProcessProxy::didReceiveMessage(IPC::Connection&, IPC::Decoder&) + 44 9 WebKit 0xe3f054 IPC::Connection::dispatchMessage(WTF::UniqueRef<IPC::Decoder>) + 252 10 WebKit 0x332d4 IPC::Connection::dispatchIncomingMessages() + 744 11 JavaScriptCore 0x58a7c WTF::RunLoop::performWork() + 204 12 JavaScriptCore 0x599a4 WTF::RunLoop::performWork(void*) + 36 13 CoreFoundation 0x56328 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 14 CoreFoundation 0x562bc __CFRunLoopDoSource0 + 176 15 CoreFoundation 0x53dc0 __CFRunLoopDoSources0 + 244 16 CoreFoundation 0x52fbc __CFRunLoopRun + 840 17 CoreFoundation 0x52830 CFRunLoopRunSpecific + 588 18 GraphicsServices 0x11c4 GSEventRunModal + 164 19 UIKitCore 0x3d2eb0 -[UIApplication _run] + 816 20 UIKitCore 0x4815b4 UIApplicationMain + 340 21 APP1 0xa2f80 main + 21 (AppDelegate.swift:21) 22 ??? 0x1c234eec8 (シンボルが不足しています) Steps: WebView: WKWebView Message passing: WKScriptMessageHandler → passing data from Angular → Swift WKWebView is long-lived and reused Native is using WKUserContentController.add(_:name:) to register handlers Crashes are intermittent (hard to reproduce), but often follow: Screen sleep/wake Push notification open Angular calling native immediately after resume Questions: Has anyone seen this specific crash pattern involving CFRelease and WKScriptMessageHandler? Are there known WebKit or CoreFoundation bugs related to WKScriptMessageHandler and retained URLs or message content? Thank you for your help!
1
0
222
Jul ’25
How to customize UIActivityViewController
We are currently developing an enterprise iOS application and are in the process of implementing Data Leakage Protection (DLP) features. As part of this effort, we need to control the available actions and target applications presented within the UIActivityViewController. Specifically, we would like to programmatically filter or restrict certain activities and destination apps shown in the share sheet based on user-specific permissions. These permissions will be dynamically evaluated and updated at runtime. This type of functionality is supported by the Microsoft Intune SDK. However, our objective is to implement this behavior natively within our application without relying on any third-party libraries. Could you please advise on the recommended approach or available APIs to achieve this level of control over the UIActivityViewController?
4
0
252
Aug ’25