I'll describe my crash with an example, looking for some insights into the reason why this is happening.
@objc public protocol LauncherContainer {
var launcher: Launcher { get }
}
@objc public protocol Launcher: UIViewControllerTransitioningDelegate {
func initiateLaunch(url: URL, launchingHotInstance: Bool)
}
@objc final class LauncherContainer: NSObject, LauncherContainer, TabsContentCellTapHandler {
...
init(
...
) {
...
super.init()
}
...
//
// ContentCellTapHandler
//
public func tabContentCellItemDidTap(
tabId: String
) {
...
launcher.initiateNewTabNavigation(
tabId: tabId // Crash happens here
)
}
public class Launcher: NSObject, Launcher, FooterPillTapHandler {
public func initiateNewTabNavigation(tabId: String) {
...
}
}
public protocol TabsContentCellTapHandler: NSObject {
func tabContentCellItemDidTap(
tabId: String,
}
Crash stack last 2 lines are- libswiftCore.dylib swift_unknownObjectRetain libswiftCore.dylib String._bridgeToObjectiveCImpl()
String._bridgeToObjectiveCImpl() gets called when the caller and implementation is in Swift file
I believe due to @objc class LauncherContainer there'd be bridging header generated. Does that mean tabId passed to tabContentCellItemDidTap is a String but the one passed to initiateNewTabNavigation is NSString?
TabId is UUID().uuidString if that helps. Wondering if UUID().uuidString has something to do with this.
Thanks a ton for helping. Please find attached screenshot of the stack trace.
Post
Replies
Boosts
Views
Activity
In my project, i have a Swift class with a class level property of type string. Like this :
class TWSwiftString {
var pString:String!
init(_ pString: String) {
self.pString = pString
}
}
I am creating intance of this class and then creating a opaque pointer to this intance. Like this :
let str = TWSwiftString("World")
// Increasing RC by 1
strptr = Unmanaged.passRetained(str).toOpaque()
Now using this opaque pointer i want to modify the value of pString by directly operating on memory. Like this:
withUnsafeMutablePointer(to: &strptr.pString) { strPointer in
strPointer.pointee = "World"
}
Although i am able to modify pString like this and print. Lets assume i have a approach to make sure memory remains valid when it is operated on and freeing of memory is also handled somehow .
Will this approach work if i have 100s of intance of this string which are being operated in this manner ? What if the size of new value is greater than existing string value ? For this i am thinking of chunk of memory initially and then keep on increasing size of it as bigger string then this chunk comes. Does this approach seems feasible ? Any other problems i can encounter by using this approach ?
Chatgpt gave this answer :
To directly update the memory of a Swift class’s property, particularly to alter a String property, is generally discouraged due to Swift's memory safety model. However, if we want to access and modify a class property directly, the best practice is to use a property accessor, as manually altering memory could lead to undefined behavior or even crashes. Why Direct Memory Manipulation Is Risky When you attempt to manipulate memory directly, especially with Swift’s memory model, you might alter not only the value but also the memory layout of Swift’s String type, which could break things internally. The Swift compiler may store String differently based on the internal structure, so even if we manage to locate the correct memory address, directly modifying it is unreliable.
do you have any opinion around chatgpt resoponse ?
I am using swiftui lately in my iOS mobile app, The Mobile app already has a pipeline that detect any experimental features and throw an error
I am using swift 5 and as you all know SwiftUI is using some of OpaqueTypeErasure utility types like "some"
I heard that in swift 6 the OpaqueTypeErasure is not experimental anymore
But upgrading the app swift version will be a very long process
Also changing the pipeline will be a very long and tiring process
So i want to know if there is a way to remove OpaqueTypeErasure from SwiftUI and what is the alternatives for bypassing the error that being thrown from the pipeline
i have macos 15 and xcode 16 swift 6 and want to make apps
to run on macintosh.
i know the syntax of this programming language, but i need
informations like which libraries i have to import for func's
which name i do not know, and parameters i have not found
on websites or the tutorial on swift.
i need procedures like
open window at x,y,width,height
draw rectangle at x,y,width,height,color
draw text at x,y,width,height,color,size
read keyboard-letter,up/dn,shift
read mouse x,y,buttons
I have a problem with the following code, I am not being notified of changes to the progress property of my Job object, which is @Observable... This is a command-line Mac application (the same code works fine in a SwiftUI application).
I must have missed something?
do {
let job = AsyncJob()
withObservationTracking {
let progress = job.progress
} onChange: {
print("Current progress: \(job.progress)")
}
let _ = try await job.run()
print("Done...")
} catch {
print(error)
}
I Try this without any success:
@main
struct MyApp {
static func main() async throws {
// my code here
}
}
I have a Package.swift
// swift-tools-version: 5.9
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "SharedUI",
defaultLocalization: "en_US",
platforms: [.iOS(.v16)],
products: [
.library(
name: "SharedUI",
targets: [
"AppTheme",
]
),
],
dependencies: [
.package(url: "https://github.com/apple/swift-markdown.git", "0.2.0"..<"0.3.0"),
],
targets: [
.target(
name: "AppTheme",
dependencies: [
.product(name: "Markdown", package: "swift-markdown"),
],
path: "AppTheme"
),
]
)
Run swift package show-dependencies shows error
yuantong-macbookpro2:Downloads yuantong$ swift package show-dependencies
Fetching https://github.com/apple/swift-markdown.git from cache
Fetched https://github.com/apple/swift-markdown.git (0.67s)
error: Couldn’t get the list of tags:
fatal: cannot use bare repository '/Users/yuantong/Downloads/.build/repositories/swift-markdown-b692ce3c' (safe.bareRepository is 'explicit')
which I think used to work before Xcode 15.
Hi,
Considering this method I'd like to test:
public func play(_ soundFileName: String, shouldLoop: Bool) {
Task {
await dataSource.play(soundFileName, shouldLoop: shouldLoop)
}
}
Previously, with XCTest we could use an expectation and wait for it to be fulfilled:
func test()
sut.play("", shouldLoop: false)
wait(for: [mockedAudioPlayerDataSource.invokedPlayExpectation])
XCTAssertEqual(mockedAudioPlayerDataSource.invokedPlayCount, 1)
With Swift Testing, I am unsure what a unit test looks like.
Hi!
I'm trying to implement Swift 6 in my code but can't fix one problem.
Here is my code example which could be run in playground:
import UIKit
import WatchConnectivity
public final class MulticastDelegate<T>: Sendable {
nonisolated(unsafe) private var delegates = [WeakWrapper]()
public init() { }
public var isEmpty: Bool {
return delegates.isEmpty
}
public func addDelegate(_ delegate: T) {
let wrapper = WeakWrapper(value: delegate as AnyObject)
delegates.append(wrapper)
}
public func removeDelegate(_ delegate: T) {
delegates = delegates.filter { $0.value !== delegate as AnyObject }
}
public func invokeDelegates(_ invocation: (T) -> Void) {
for (index, delegate) in delegates.enumerated().reversed() {
if let delegate = delegate.value as? T {
invocation(delegate)
} else {
delegates.remove(at: index)
}
}
}
public func invokeDelegatesCheckingResponse(_ invocation: (T) -> Bool) -> Bool {
var isHandled = false
for delegate in delegates {
if let delegate = delegate.value as? T {
if invocation(delegate) {
isHandled = true
break
}
}
}
return isHandled
}
private final class WeakWrapper: Sendable {
nonisolated(unsafe) weak var value: AnyObject?
init(value: AnyObject) {
self.value = value
}
}
}
@globalActor public actor WatchActor {
public static var shared = WatchActor()
}
@MainActor
@objc public protocol WatchCommunicatorDelegate: NSObjectProtocol {
@objc optional func watchCommunicatorDidRequestDataUpdate(_ controller: WatchCommunicator)
}
@WatchActor
@objc public final class WatchCommunicator: NSObject {
private let multicastDelegate = MulticastDelegate<WatchCommunicatorDelegate>()
}
extension WatchCommunicator: @preconcurrency WCSessionDelegate {
public func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: (any Error)?) {
multicastDelegate.invokeDelegates { delegate in
Task { @MainActor in
delegate.watchCommunicatorDidRequestDataUpdate?(self)
}
}
}
public func sessionDidBecomeInactive(_ session: WCSession) {
}
public func sessionDidDeactivate(_ session: WCSession) {
}
}
I want to work with WatchCommunicator in global actor and WatchCommunicatorDelegate should be call in main actor and should have reference to WatchCommunicator.
Help please
I have a workspace with my project and a Swift Macro. When I use the "Build Documentation" command the build fails with this error:
fatal error: module map file '/Users/me/Library/Developer/Xcode/DerivedData/Project-fmdkuqlofexbqdhhitpgjnoqzyrz/Build/Intermediates.noindex/GeneratedModuleMaps-iphoneos/Macros.modulemap' not found
Is there a way around this?
Hey all!
in my personal quest to make future proof apps moving to Swift 6, one of my app has a problem when setting an artwork image in MPNowPlayingInfoCenter
Here's what I'm using to set the metadata
func setMetadata(title: String? = nil, artist: String? = nil, artwork: String? = nil) async throws {
let defaultArtwork = UIImage(named: "logo")!
var nowPlayingInfo = [
MPMediaItemPropertyTitle: title ?? "***",
MPMediaItemPropertyArtist: artist ?? "***",
MPMediaItemPropertyArtwork: MPMediaItemArtwork(boundsSize: defaultArtwork.size) { _ in
defaultArtwork
}
] as [String: Any]
if let artwork = artwork {
guard let url = URL(string: artwork) else { return }
let (data, response) = try await URLSession.shared.data(from: url)
guard (response as? HTTPURLResponse)?.statusCode == 200 else { return }
guard let image = UIImage(data: data) else { return }
nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in
image
}
}
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
the app crashes when hitting
MPMediaItemPropertyArtwork: MPMediaItemArtwork(boundsSize: defaultArtwork.size) { _ in
defaultArtwork
}
or
nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in
image
}
commenting out these two make the app work again.
Again, no clue on why.
Thanks in advance
We are getting a crash _dispatch_assert_queue_fail when the cancellationHandler on NSProgress is called.
We do not see this with iOS 17.x, only on iOS 18. We are building in Swift 6 language mode and do not have any compiler warnings.
We have a type whose init looks something like this:
init(
request: URLRequest,
destinationURL: URL,
session: URLSession
) {
progress = Progress()
progress.kind = .file
progress.fileOperationKind = .downloading
progress.fileURL = destinationURL
progress.pausingHandler = { [weak self] in
self?.setIsPaused(true)
}
progress.resumingHandler = { [weak self] in
self?.setIsPaused(false)
}
progress.cancellationHandler = { [weak self] in
self?.cancel()
}
When the progress is cancelled, and the cancellation handler is invoked. We get the crash. The crash is not reproducible 100% of the time, but it happens significantly often. Especially after cleaning and rebuilding and running our tests.
* thread #4, queue = 'com.apple.root.default-qos', stop reason = EXC_BREAKPOINT (code=1, subcode=0x18017b0e8)
* frame #0: 0x000000018017b0e8 libdispatch.dylib`_dispatch_assert_queue_fail + 116
frame #1: 0x000000018017b074 libdispatch.dylib`dispatch_assert_queue + 188
frame #2: 0x00000002444c63e0 libswift_Concurrency.dylib`swift_task_isCurrentExecutorImpl(swift::SerialExecutorRef) + 284
frame #3: 0x000000010b80bd84 MyTests`closure #3 in MyController.init() at MyController.swift:0
frame #4: 0x000000010b80bb04 MyTests`thunk for @escaping @callee_guaranteed @Sendable () -> () at <compiler-generated>:0
frame #5: 0x00000001810276b0 Foundation`__20-[NSProgress cancel]_block_invoke_3 + 28
frame #6: 0x00000001801774ec libdispatch.dylib`_dispatch_call_block_and_release + 24
frame #7: 0x0000000180178de0 libdispatch.dylib`_dispatch_client_callout + 16
frame #8: 0x000000018018b7dc libdispatch.dylib`_dispatch_root_queue_drain + 1072
frame #9: 0x000000018018bf60 libdispatch.dylib`_dispatch_worker_thread2 + 232
frame #10: 0x00000001012a77d8 libsystem_pthread.dylib`_pthread_wqthread + 224
Any thoughts on why this is crashing and what we can do to work-around it? I have not been able to extract our code into a simple reproducible case yet. And I mostly see it when running our code in a testing environment (XCTest). Although I have been able to reproduce it running an app a few times, it's just less common.
In WWDC 2023 there was a good summary of how to handle the iOS 17 Observation capability.
But despite the clear graphics, it was still ambiguous (for me.)
I want to inject a class (view-model) so that it can be used in the complete view heirarchy, and used in bindings to allow bi-directional communication.
As far as I can tell there are 2 ways of declaring the VM (alternatives 1 and 2 in my code), and 2 ways of consuming the VM in a view (alternatives 3 and 4 in my code). Using the flow-diagram I can't determine which is best.
Here's the crux of my #Observable problem.
import SwiftUI
// MARK: - Model
struct MyMod {
var title = "Hello, World!"
}
// MARK: - MVV
@Observable
class MyMVV {
var model: MyMod
init() {
self.model = MyMod()
}
}
// MARK: - App
@main
struct MyApp: App {
@Bindable var myGlobalMVV = MyMVV() // Alternative 1
// @State var myGlobalMVV = MyMVV() // Alternative 2
var body: some Scene {
WindowGroup {
ContentView()
.environment(myGlobalMVV) // inject
}
}
}
struct ContentView: View {
var body: some View {
ContentDeepHierarchyView()
}
}
struct ContentDeepHierarchyView: View {
@Environment(MyMVV.self) var myGlobalMVV // digest
var body: some View {
@Bindable var myLocalMVV = myGlobalMVV // Alternative 3
TextField("The new title", text: $myLocalMVV.model.title) // Alternative 3
TextField("The new title", text: Bindable(myGlobalMVV).model.title) // Alternative 4
}
Opinions?
underlying Objective-C module 'FirebaseSharedSwift' not found
aymodazhnyneylcscdggrsgjocui/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FirebaseSharedSwift.build/Objects-normal/x86_64/FirebaseSharedSwift.private.swiftinterface:5:19: underlying Objective-C module 'FirebaseSharedSwift' not found
Command SwiftCompile failed with a nonzero exit code
Hi, I have issue on build my react native project and got this error "Undefined symbol: _swift_willThrowTypedImpl" how can I fix it?
This is one of the worst errors you can encounter while developing with Xcode.
It looks like it's related to a problem inside the compiler itself: when there are lot of lines of code, it becomes unable to identify them all and start asking you to break down the code in smaller pieces.
Sometimes you can, sometimes not.
First of all, in your code there is FOR SURE an error, so in case of the second option, begin commenting entires sections of your code: this can lead to two options:
You commented a section that contains the error: Xcode give you the preview and you check the commented section to find the error
You commented enough code to let the compiler do its job, and you'll have the normal error reported in your code: again, fix it!
Once errors have been fixed, normally you can uncomment what you excluded and all will go up and ok again.
The most common errors that can lead to this behavior (but it's just a hint) are those involving parameters got or passed to other SwiftUI objects:
parameters label (mistyped, missing, exceeding)
parameters values (not $/& present, $/& present but not required)
parameters types (you passed a wrong type)
Well, I hope that this post could be useful to others that, like I did, are struggling a lot to understand the exact nature of this peculiar error.
Code well and Prosper!
We started building our project in XCode 16 only to find a super weird crash that was 100% reproducible.
I couldn't really understand why it was crashing, so I tried to trim down the problematic piece of code to something that I could provide in a side project. The actual piece of code crashing for us is significantly different, but this small example showcases the crash as well.
https://github.com/Elih96/XCode16CrashReproducer
our observation is, that this combination of async let usage + struct structure leads to a SIGABRT crash in the concurrency library.
In both the main project and the example project, moving away from async let and using any other concurrency mechanism fixes the crash.
This was reproducible only on Xcode 16 with iOS 15 set as minimum deployment for the target. It works fine on Xcode 15, and if we bump the min deployment to 16 on Xcode 16, it also runs fine. I've attached a small project that reproduces the error.
I'm sure I didn't provide the ideal reproduction scenario, but that's what I managed to trim it down to. Making random changes such as removing some properties from the B struct or remove the:
let _ = A().arrayItems.map { _ in "123" }
will stop the crash from happening, so I just stopped making changes.
The stack trace from the crash:
frame #0: 0x00000001036d1008 libsystem_kernel.dylib`__pthread_kill + 8
frame #1: 0x0000000102ecf408 libsystem_pthread.dylib`pthread_kill + 256
frame #2: 0x00000001801655c0 libsystem_c.dylib`abort + 104
frame #3: 0x000000020a8b7de0 libswift_Concurrency.dylib`swift::swift_Concurrency_fatalErrorv(unsigned int, char const*, char*) + 28
frame #4: 0x000000020a8b7dfc libswift_Concurrency.dylib`swift::swift_Concurrency_fatalError(unsigned int, char const*, ...) + 28
frame #5: 0x000000020a8baf54 libswift_Concurrency.dylib`swift_task_dealloc + 124
frame #6: 0x000000020a8b72c8 libswift_Concurrency.dylib`asyncLet_finish_after_task_completion(swift::AsyncContext*, swift::AsyncLet*, void (swift::AsyncContext* swift_async_context) swiftasynccall*, swift::AsyncContext*, void*) + 72
* frame #7: 0x000000010344e6e4 CrashReproducer.debug.dylib`closure #1 in closure #1 in CrashReproducerApp.body.getter at CrashReproducerApp.swift:17:46
frame #8: 0x00000001cca0a560 SwiftUI`___lldb_unnamed_symbol158883
frame #9: 0x00000001cca09fc0 SwiftUI`___lldb_unnamed_symbol158825
frame #10: 0x00000001cca063a0 SwiftUI`___lldb_unnamed_symbol158636
frame #11: 0x00000001cca09268 SwiftUI`___lldb_unnamed_symbol158726
I've just upgraded to Xcode 16 and my app now fails when attempting to read a text file from the main bundle. It finds the path but can't open the file so this snippet prints: "File read error for path: /private/var/containers/Bundle/Application/AABAD428-96BC-4B34-80B4-97FA80B77E58/Test.app/csvfile.csv"
This worked fine up to 15.4. Has something changed? Thanks.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let bundle = Bundle.main
let path = bundle.path(forResource: "csvfile", ofType: "csv")!
do {
let content = try String(contentsOfFile: path, encoding: String.Encoding.ascii)
} catch {
print("File read error for path: \(String(describing: path))")
}
}
}
Here is my code:
`
// A 3rd-party class I must use.
class MySession{
init() async throws {
// ..
}
}
actor SessionManager{
private var mySession: MySession? // The MySession is not Sendable
func createSession() async {
do {
mySession = try await MySession()
log("getOrCreateSession() End, success.")
} catch {
log("getOrCreateSession() End, failure.")
}
}
}`
I get this warning: "Non-sendable type 'MySession' returned by implicitly asynchronous call to a nonisolated function cannot cross the actor boundary."
How can this be fixed?
When swizzling NSURLRequest initialiser and returning a mutable copy, the original instance does not get deallocated and eventually gets leaked and a crash follows after that.
Here's the swizzling setup:
static func swizzleInit() {
let initSel = NSSelectorFromString("initWithURL:cachePolicy:timeoutInterval:")
guard let initMethod = class_getInstanceMethod(NSClassFromString("NSURLRequest"), initSel) else {
return
}
let origInitImp = method_getImplementation(initMethod)
let block: @convention(block) (AnyObject, Any, NSURLRequest.CachePolicy, TimeInterval) -> NSURLRequest = { _self, url, policy, interval in
typealias OrigInit = @convention(c) (AnyObject, Selector, Any, NSURLRequest.CachePolicy, TimeInterval) -> NSURLRequest
let origFunc = unsafeBitCast(origInitImp, to: OrigInit.self)
let request = origFunc(_self, initSel, url, policy, interval)
return request.tagged()
}
let newImplementation = imp_implementationWithBlock(block as Any)
method_setImplementation(initMethod, newImplementation)
}
// create a mutable copy if needed and add a header
private func tagged() -> NSURLRequest {
guard let mutableRequest = self as? NSMutableURLRequest ?? self.mutableCopy() as? NSMutableURLRequest else {
return self
}
mutableRequest.setValue("test", forHTTPHeaderField: "test")
return mutableRequest
}
Then, we have a few test cases:
// memory leak and crash
func testSwizzleNSURLRequestInit() {
let request = NSURLRequest(url: URL(string: "https://example.com")!)
XCTAssertEqual(request.value(forHTTPHeaderField: "test"), "test")
}
// no crash, as the request is mutable, so no copy is created
func testSwizzleNSURLRequestInit2() {
let request = URLRequest(url: URL(string: "https://example.com")!)
XCTAssertEqual(request.value(forHTTPHeaderField: "test"), "test")
}
// no crash, as the request is mutable, so no copy is created
func testSwizzleNSURLRequestInit3() {
let request = NSMutableURLRequest(url: URL(string: "https://example.com")!)
XCTAssertEqual(request.value(forHTTPHeaderField: "test"), "test")
}
// no crash, as the new instance does not get deallocated
// when the test method completes (?)
var request: NSURLRequest?
func testSwizzleNSURLRequestInit4() {
request = NSURLRequest(url: URL(string: "https://example.com")!)
XCTAssertEqual(request?.value(forHTTPHeaderField: "test"), "test")
}
It appears a memory leak occurs only when any other instance except for the original one is being returned from the initialiser.
Is there a workaround to prevent the leak, while allowing for modifications of all requests?
Hi there, this is my first time posting here. I've heard that some of the apple developers are usually active on these forums, so I've decided to shoot my shot, because this question was driving me crazy for a few days now and nobody could yet give me a clear view on what's actually happening.
Here is the first snippet of the code
class Animal {
var name = "Fischer"
var command: () -> Void = { }
deinit {
print(#function, #line)
}
}
do {
var pet: Animal? = Animal()
pet?.command = { print(pet?.name ?? "Bobby") }
}
This code causes a memory leak, because
Reference 'pet' is created.
Independent copy of the reference 'pet' is created inside the closure. now there are two references to the same object, which are 'pet' outside the closure and 'pet' inside the closure.
As we exit the 'do' scope, the 'pet' reference is deleted, but ARC does not deallocate the object due to the strong reference 'pet', that is still referencing to the same object.
And all of that causes a memory leak.
Now here is the code, that is pretty similar, except for the fact, that we assign a nil to the 'pet' reference
class Animal {
var name = "Fischer"
var command: () -> Void = { }
deinit {
print(#function, #line)
}
}
do {
var pet: Animal? = Animal()
pet?.command = { print(pet?.name ?? "Bobby") }
pet = nil
}
And boom! deinit is called, meaning that the object was deallocated, but how? Why was the object deallocated? If we are deleting the exact same reference, that was deleted by the end of the 'do' scope in the first snippet? Am I misunderstanding something? I really hope this post will find the right people, since I could not even find appropriate tags for that.