Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

How do you create an actor with a non-sendable member variable that is initialized with async init()?
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?
1
0
271
Oct ’24
Memory leaks caused by closures
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.
4
0
330
Oct ’24
Under Swift 6 on Sequoia, why is ContiguousArray suddenly so slow to allocate
I generate images with command line apps in Swift on MacOS. Under the prior Xcode/MacOS my code had been running at the same performance for years. Converting to Swift 6 (no code changes) and running on Sequoia, I noticed a massive slowdown. Running Profile, I tracked it down to allow single line: var values = ContiguousArray<Double>(repeating: 0.0, count: localData.options.count) count for my current test case is 4, so its allocating 4 doubles at a time, around 40,000 times in this test. This one line takes 42 seconds out of a run time of 52 seconds. With the profile shown as: 26 41.62 s  4.8% 26.00 ms specialized ContiguousArray.init(_uninitializedCount:) 42 41.57 s  4.8% 42.00 ms _ContiguousArrayBuffer.init(_uninitializedCount:minimumCapacity:) 40730 40.93 s  4.7% 40.73 s _swift_allocObject_ 68 68.00 ms  0.0% 68.00 ms std::__1::pair<MallocTypeCacheEntry*, unsigned int> swift::ConcurrentReadableHashMap<MallocTypeCacheEntry, swift::LazyMutex>::find<unsigned int>(unsigned int const&, swift::ConcurrentReadableHashMap<MallocTypeCacheEntry, swift::LazyMutex>::IndexStorage, unsigned long, MallocTypeCacheEntry*) 7 130.00 ms  0.0% 7.00 ms swift::swift_slowAllocTyped(unsigned long, unsigned long, unsigned long long) which is clearly inside the OS allocator somewhere. What happened? Previously this would have taken closer to 8 seconds or so for the entire run.
3
0
298
Oct ’24
Symbol not found: _swift_getTypeByMangledNameInContext2
We have MacOS application which uses Network Extensions. When building it with XCode 15 and 15.0.1 the extension crashes on Intel based Macs with the following error: Symbol not found: _swift_getTypeByMangledNameInContext2 Expected in: /usr/lib/swift/libswiftCore.dylib We tested it on Big Sur and Ventura with the same outcome. On Ventura when running on Intel based Mac libswiftCore.dylib really doesn't provide this symbol: nm -g libswiftCore.dylib | grep Mangle 00007ff80faf6150 T _$ss031_getFunctionFullNameFromMangledD007mangledD0SSSgSS_tF 00007ff80fcc4460 T _swift_getFunctionFullNameFromMangledName 00007ff80fcc40b0 T _swift_getMangledTypeName 00007ff80fcf7ed0 T _swift_getTypeByMangledName 00007ff80fcf8230 T _swift_getTypeByMangledNameInContext 00007ff80fcf8370 T _swift_getTypeByMangledNameInContextInMetadataState 00007ff80fcf7d90 T _swift_getTypeByMangledNameInEnvironment 00007ff80fcf80f0 T _swift_getTypeByMangledNameInEnvironmentInMetadataState 00007ff80fcfb460 T _swift_getTypeByMangledNode Is there any workaround for this issue? Crash log is the following: Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 dyld 0x000000010a165f7a __abort_with_payload + 10 1 dyld 0x000000010a18ef40 abort_with_payload_wrapper_internal + 80 2 dyld 0x000000010a18ef72 abort_with_payload + 9 3 dyld 0x000000010a10f14a dyld::halt(char const*) + 672 4 dyld 0x000000010a10f274 dyld::fastBindLazySymbol(ImageLoader**, unsigned long) + 167 5 libdyld.dylib 0x00007fff203b3376 dyld_stub_binder + 282 6 ??? 0x0000000104b086a0 0 + 4373644960 7 com.xxxx.Tunnel 0x00000001049d318a 0x10489e000 + 1266058 8 com.xxxx.Tunnel 0x00000001049df35d 0x10489e000 + 1315677 9 com.xxxx.Tunnel 0x00000001048a0765 0x10489e000 + 10085 10 com.apple.ExtensionKit 0x00007fff31bda683 __112-[EXConcreteExtensionContextVendor _beginRequestWithExtensionItems:listenerEndpoint:withContextUUID:completion:]_block_invoke + 808 11 libdispatch.dylib 0x00007fff201ec5dd _dispatch_call_block_and_release + 12 12 libdispatch.dylib 0x00007fff201ed7c7 _dispatch_client_callout + 8 13 libdispatch.dylib 0x00007fff201f9b86 _dispatch_main_queue_callback_4CF + 940 14 com.apple.CoreFoundation 0x00007fff204ce356 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9 15 com.apple.CoreFoundation 0x00007fff20490188 __CFRunLoopRun + 2745 16 com.apple.CoreFoundation 0x00007fff2048efe2 CFRunLoopRunSpecific + 567 17 com.apple.Foundation 0x00007fff21151fa1 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 212 18 com.apple.Foundation 0x00007fff211e0384 -[NSRunLoop(NSRunLoop) run] + 76 19 libxpc.dylib 0x00007fff200e53dd _xpc_objc_main + 825 20 libxpc.dylib 0x00007fff200e4e65 xpc_main + 437 21 com.apple.Foundation 0x00007fff211732bd -[NSXPCListener resume] + 262 22 com.apple.pluginkit.framework 0x00007fff2b288273 0x7fff2b26d000 + 111219 23 com.apple.pluginkit.framework 0x00007fff2b287efb 0x7fff2b26d000 + 110331 24 com.apple.pluginkit.framework 0x00007fff2b288639 0x7fff2b26d000 + 112185 25 com.apple.ExtensionKit 0x00007fff31be6d05 EXExtensionMain + 70 26 com.apple.Foundation 0x00007fff211e2479 NSExtensionMain + 208 27 libdyld.dylib 0x00007fff203b4621 start + 1
4
0
962
Dec ’23
Command SwiftCompile failed with a nonzero exit code. in xocde 16 and 15 where as it was working fine in xcode 14.3
My project’s source code was building, running, and archiving successfully in Xcode 14.3. However, after upgrading to Xcode 15, I began encountering the error: “Command SwiftCompile failed with a nonzero exit code.” I couldn't resolve the issue, so I decided to continue using Xcode 14.3. Recently, I upgraded to macOS Sequoia and also updated to Xcode 16. Unfortunately, the same error persists in the latest Xcode: “Command SwiftCompile failed with a nonzero exit code.” The unfortunate part is that Xcode 14.3 no longer works after the macOS upgrade. Whenever I try to run the code, I get the following popup.
10
0
850
Sep ’24
Can i use c++ in swift app project
Can i use c++ library with c library in swift app project Hello. I want to use a C++ library in my Swift app project. First, our company has an internal solution library. When built, it generates a Static Library in '.a' format, and we use it by connecting the library's Header to the App_Bridging_Header. There's no problem with this part. However, the new feature now includes C++. It also generates a Static Library in '.a' format. So, I tried to use the same method and created an App_Bridging_Header. But an error occurs, and I can't proceed. The first error occurs in the library file: 'iostream' file not found The second error occurs in the App_Bridging_Header: failed to emit precompiled header '/Users/kimjitae/Library/Developer/Xcode/DerivedData/ddddd-glmnoqrwdrgarrhjulxjmalpyikr/Build/Intermediates.noindex/PrecompiledHeaders/ddddd-Bridging-Header-swift_3O89L0OXZ0CPD-clang_188AW1HK8F0Q3.pch' for bridging header '/Users/kimjitae/Desktop/enf4/ddddd/ddddd/ddddd-Bridging-Header.h' Our library is developed in C++ using Xcode, and there's no problem when we run and build just the library project. The build succeeds, and the '.a' file is generated correctly. However, when we try to connect it with the app, the above problems occur. Could there be a problem because we also need to use the existing C library alongside this? The build is successful in an app project created with Objective-C.
4
0
255
Oct ’24
Casting `[String: Any]` to `[String: any Sendable]`
I have a simple wrapper class around WCSession to allow for easier unit testing. I'm trying to update it to Swift 6 concurrency standards, but running into some issues. One of them is in the sendMessage function (docs here It takes [String: Any] as a param, and returns them as the reply. Here's my code that calls this: @discardableResult public func sendMessage(_ message: [String: Any]) async throws -&gt; [String: Any] { return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation&lt;[String: Any], Error&gt;) in wcSession.sendMessage(message) { response in continuation.resume(returning: response) // ERROR HERE } errorHandler: { error in continuation.resume(throwing: error) } } } However, I get this error: Sending 'response' risks causing data races; this is an error in the Swift 6 language mode Which I think is because Any is not Sendable. I tried casting [String: Any] to [String: any Sendable] but then it says: Conditional cast from '[String : Any]' to '[String : any Sendable]' always succeeds Any ideas on how to get this to work?
3
1
365
Oct ’24
Swift Testing not recognising tests
For my app I was trying to write some tests to ensure the functionality of all features. As I am using Xcode 16.0 I thought I might use Swift testing which was newly introduced and replaces XCTest. I created a new test target with Swift Testing and tried to run the first test, which was created automatically by the system. struct FinancialTests { @Test func testExample() async throws { #expect(true) } } Xcode is also showing the test diamond next to the function so I clicked on it to execute it. The app started to build and the build ended successfully. The the next step was testing. And after waiting for 10 minutes or so, no test was executed. First I thought maybe the test was not found, but in the test case overview all tests were shown: The run only shows this: Can someone help me to get this running. Many thanks!
3
1
329
Sep ’24
Can't link Obj-C Enum Symbol with DocC
Hi all, I am trying to use this guide to link directly to symbols in my documentation. But I am unable to get it to link to an Objective-C enum case. For example ``EnumNameType/EnumNameMyCase`` does not create a link. It works fine for method names, etc. I have tried all of the combinations I can think of, but I can't get it to work. Any help is much appreciated!
3
0
296
Oct ’24
Crash with Incorrect actor executor assumption
I'm seeing a crash compiling with Swift 6 that I can reproduce with the following code. It crashes with "Incorrect actor executor assumption". Is there something that the compiler should be warning about so that this isn't a runtime crash? Note - if I use a for in loop instead of the .forEach closure, the crash does not happen. Is the compiler somehow inferring the wrong isolation domain for the closure? import SwiftUI struct ContentView: View { var body: some View { Text("Hello, world!") .task { _ = try? await MyActor(store: MyStore()) } } } actor MyActor { var credentials = [String]() init(store: MyStore) async throws { try await store.persisted.forEach { credentials.append($0) } } } final class MyStore: Sendable { var persisted: [String] { get async throws { return ["abc"] } } } The stack trace is: * thread #6, queue = 'com.apple.root.user-initiated-qos.cooperative', stop reason = signal SIGABRT frame #0: 0x0000000101988f30 libsystem_kernel.dylib`__pthread_kill + 8 frame #1: 0x0000000100e2f124 libsystem_pthread.dylib`pthread_kill + 256 frame #2: 0x000000018016c4ec libsystem_c.dylib`abort + 104 frame #3: 0x00000002444c944c libswift_Concurrency.dylib`swift::swift_Concurrency_fatalErrorv(unsigned int, char const*, char*) + 28 frame #4: 0x00000002444c9468 libswift_Concurrency.dylib`swift::swift_Concurrency_fatalError(unsigned int, char const*, ...) + 28 frame #5: 0x00000002444c90e0 libswift_Concurrency.dylib`swift_task_checkIsolated + 152 frame #6: 0x00000002444c63e0 libswift_Concurrency.dylib`swift_task_isCurrentExecutorImpl(swift::SerialExecutorRef) + 284 frame #7: 0x0000000100d58944 IncorrectActorExecutorAssumption.debug.dylib`closure #1 in MyActor.init($0="abc") at <stdin>:0 frame #8: 0x0000000100d58b94 IncorrectActorExecutorAssumption.debug.dylib`partial apply for closure #1 in MyActor.init(store:) at <compiler-generated>:0 frame #9: 0x00000001947f8c80 libswiftCore.dylib`Swift.Sequence.forEach((τ_0_0.Element) throws -> ()) throws -> () + 428 * frame #10: 0x0000000100d58748 IncorrectActorExecutorAssumption.debug.dylib`MyActor.init(store=0x0000600000010ba0) at ContentView.swift:27:35 frame #11: 0x0000000100d57734 IncorrectActorExecutorAssumption.debug.dylib`closure #1 in ContentView.body.getter at ContentView.swift:14:32 frame #12: 0x0000000100d57734 IncorrectActorExecutorAssumption.debug.dylib`closure #1 in ContentView.body.getter at ContentView.swift:14:32 frame #13: 0x00000001d1817138 SwiftUI`(1) await resume partial function for partial apply forwarder for closure #1 () async -> () in closure #1 (inout Swift.TaskGroup<()>) async -> () in closure #1 () async -> () in SwiftUI.AppDelegate.application(_: __C.UIApplication, handleEventsForBackgroundURLSession: Swift.String, completionHandler: () -> ()) -> () frame #14: 0x00000001d17b1e48 SwiftUI`(1) await resume partial function for dispatch thunk of static SwiftUI.PreviewModifier.makeSharedContext() async throws -> τ_0_0.Context frame #15: 0x00000001d19c10c0 SwiftUI`(1) await resume partial function for generic specialization <()> of reabstraction thunk helper <τ_0_0 where τ_0_0: Swift.Sendable> from @escaping @isolated(any) @callee_guaranteed @async () -> (@out τ_0_0) to @escaping @callee_guaranteed @async () -> (@out τ_0_0, @error @owned Swift.Error) frame #16: 0x00000001d17b1e48 SwiftUI`(1) await resume partial function for dispatch thunk of static SwiftUI.PreviewModifier.makeSharedContext() async throws -> τ_0_0.Context
2
0
529
Oct ’24
Interpreting received "Data" object in cpp
Hello Everyone, I have a use case where I wanted to interpret the "Data" object received as a part of my NWConnection's recv call. I have my interpretation logic in cpp so in swift I extract the pointer to the raw bytes from Data and pass it to cpp as a UnsafeMutableRawPointer. In cpp it is received as a void * where I typecast it to char * to read data byte by byte before framing a response. I am able to get the pointer of the bytes by using // Swift Code // pContent is the received Data if let content = pContent, !content.isEmpty { bytes = content.withUnsafeBytes { rawBufferPointer in guard let buffer = rawBufferPointer.baseAddress else { // return with null data. } // invoke cpp method to interpret data and trigger response. } // Cpp Code void InterpretResponse (void * pDataPointer, int pDataLength) { char * data = (char *) pDataPointer; for (int iterator = 0; iterator < pDataLength; ++iterator ) { std::cout << data<< std::endl; data++; } } When I pass this buffer to cpp, I am unable to interpret it properly. Can someone help me out here? Thanks :) Harshal
3
0
568
Oct ’24
App crash on iPhone 11 Pro Max version 18.0 which build on Xcode 16.0
thread #1, stop reason = signal SIGABRT frame #0: 0x00000001a95985a8 dyld__abort_with_payload + 8 frame #1: 0x00000001a959f208 dyldabort_with_payload_wrapper_internal + 104 frame #2: 0x00000001a959f23c dyldabort_with_payload + 16 frame #3: 0x00000001a95364c8 dylddyld4::halt(char const*, dyld4::StructuredError const*) + 300 frame #4: 0x00000001a9541f60 dylddyld4::prepare(dyld4::APIs&, dyld3::MachOAnalyzer const*) + 4124 frame #5: 0x00000001a95667a8 dylddyld4::start(dyld4::KernelArgs*, void*, void*)::$_0::operator()() const + 544 frame #6: 0x00000001a955fb1c dyld`start + 2188
1
0
262
Sep ’24
Actor and the Singleton Pattern
As I migrate my apps to Swift 6 one by one, I am gaining a deeper understanding of concurrency. In the process, I am quite satisfied to see the performance benefits of parallel programming being integrated into my apps. At the same time, I have come to think that actor is a great type for addressing the 'data race' issues that can arise when using the 'singleton' pattern with class. Specifically, by using actor, you no longer need to write code like private let lock = DispatchQueue(label: "com.singleton.lock") to prevent data races that you would normally have to deal with when creating a singleton with a class. It reduces the risk of developer mistakes. import EventKit actor EKDataStore: Sendable { static let shared = EKDataStore() let eventStore: EKEventStore private init() { self.eventStore = EKEventStore() } } Of course, since a singleton is an object used globally, it can become harder to manage dependencies over time. There's also the downside of not being able to inject dependencies, which makes testing more difficult. I still think the singleton pattern is ideal for objects that need to be maintained throughout the entire lifecycle of the app with only one instance. The EKDataStore example I gave is such an object. I’d love to hear other iOS developers' opinions, and I would appreciate any advice on whether I might be missing something 🙏
1
0
443
Sep ’24
error: memory read failed for 0x10
Issues Integrating FaceTec SDK into a Custom iOS Framework Hi Community, I am working on a custom iOS framework that integrates FaceTec SDK for biometric authentication, but I am facing issues with properly running the SDK within my framework. Below is the context and specific issues I need help with: Context: I have created a framework that includes a UIViewController called FinishViewController. This controller is responsible for managing the FaceTec SDK session. Below is a simplified snippet of the code used to initialize and handle FaceTec SDK: import UIKit import FaceTecSDK import LocalAuthentication class FinishViewController: UIViewController, URLSessionDelegate{ var utils: SampleAppUtilities! var latestProcessor: Processor! var latestExternalDatabaseRefID: String = "" var latestSessionResult: FaceTecSessionResult! var latestIDScanResult: FaceTecIDScanResult! @IBOutlet weak var elTelon: UIView! var isRealPerson = false var isNotSuccessful = false var isCancelled = false override func viewDidLoad() { super.viewDidLoad() utils = SampleAppUtilities(vc: self) // Initialize FaceTec SDK Config.initializeFaceTecSDKFromAutogeneratedConfig(completion: { initializationSuccessful in if(initializationSuccessful) { self.onFaceTecSDKInitializationSuccess() } else { self.onFaceTecSDKInitializationFailure() } }) DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [self] in getSessionToken() { sessionToken in _ = LivenessCheckProcessor(sessionToken: sessionToken, fromViewController: self) .lvResponseDelegate = self //self.latestProcessor = AuthenticateProcessor(sessionToken: sessionToken, fromViewController: self) } } // Do any additional setup after loading the view. } func onFaceTecSDKInitializationFailure() { // Displays the FaceTec SDK Status to text field if init failed self.utils.displayStatus(statusString: "\(FaceTec.sdk.description(for: FaceTec.sdk.getStatus()))") } func onFaceTecSDKInitializationSuccess() { // self.utils.enableButtons(shouldEnable: true) // Set your FaceTec Device SDK Customizations. ThemeHelpers.setAppTheme(theme: utils.currentTheme) // Set the sound files that are to be used for Vocal Guidance. // Set the strings to be used for group names, field names, and placeholder texts for the FaceTec ID Scan User OCR Confirmation Screen. SampleAppUtilities.setOCRLocalization() let currentTheme = Config.wasSDKConfiguredWithConfigWizard ? "Config Wizard Theme" : "FaceTec Theme" utils.handleThemeSelection(theme: currentTheme) self.utils.displayStatus(statusString: "Initialized Successfully.") } func onComplete() { if !self.latestProcessor.isSuccess() { // Reset the enrollment identifier. self.latestExternalDatabaseRefID = ""; } } func getSessionToken(sessionTokenCallback: @escaping (String) -> ()) { let endpoint = Config.BaseURL + "/session-token" let request = NSMutableURLRequest(url: NSURL(string: endpoint)! as URL) request.httpMethod = "GET" // Required parameters to interact with the FaceTec Managed Testing API. request.addValue(Config.DeviceKeyIdentifier, forHTTPHeaderField: "X-Device-Key") request.addValue(FaceTec.sdk.createFaceTecAPIUserAgentString(""), forHTTPHeaderField: "User-Agent") request.addValue(FaceTec.sdk.createFaceTecAPIUserAgentString(""), forHTTPHeaderField: "X-User-Agent") let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main) let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in // Ensure the data object is not nil otherwise callback with empty dictionary. guard let data = data else { print("Exception raised while attempting HTTPS call.") return } if let responseJSONObj = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: AnyObject] { if((responseJSONObj["sessionToken"] as? String) != nil) { sessionTokenCallback(responseJSONObj["sessionToken"] as! String) return } else { print("Exception raised while attempting HTTPS call.") } } }) task.resume() } func getLatestExternalDatabaseRefID() -> String { return latestExternalDatabaseRefID; } func setLatestSessionResult(sessionResult: FaceTecSessionResult) { latestSessionResult = sessionResult print("The latestSessionResult is: ", latestSessionResult!) } @IBAction func finish(_ sender: Any) { AppConfig.shared.intentosCaptura = 1 self.performSegue(withIdentifier: "unwindToRoot", sender: self) } } When I try to run the SDK, no initial compilation or runtime errors occur, but the SDK does not start as expected and there are no clear indications or errors in the console to help me diagnose the problem. I have checked the wiring of all the IBOutlet and IBAction, and everything seems to be in order. Are there any special considerations I should be aware of when integrating FaceTec SDK into a framework rather than an application directly? Are there any best practices for managing SDK initialization or view lifecycles within an iOS framework? Has anyone faced similar issues when integrating third-party SDKs into custom frameworks and how did they resolve them?
1
0
298
Sep ’24
Stored property 'base' of 'Sendable'-conforming struct 'AnyShape' has non-sendable type '(CGRect) -> Path'; this is an error in the Swift 6 language mode
Since I updated my project I'm getting this error Stored property 'base' of 'Sendable'-conforming struct 'AnyShape' has non-sendable type '(CGRect) -> Path'; this is an error in the Swift 6 language mode I get this error at that struct, more specifically on the base variable public struct AnyShape: Shape { private var base: (CGRect) -> Path public init<S: Shape>(shape: S) { base = shape.path(in:) } public func path(in rect: CGRect) -> Path { base(rect) } } I have no idea how to solve this issue, I've been looking on the internet for same issues and get nothing yet
1
0
453
Sep ’24
Swift Concurrency crash in iOS 18 and 18.1 in withTaskCancellationHandler
We are seeing a swift concurrency related crash in iOS 18 and iOS 18.1 that has no direct link to any part of my code base in the stack trace. We are not able to reproduce locally but see it in the Organizer. The crash seems to come from withTaskCancellationHandler in Concurrency.swift Incident Identifier: C5331198-3922-471F-8E39-57186BBB962B Distributor ID: com.apple.AppStore Hardware Model: iPhone16,2 Process: MyApp [866] Path: /private/var/containers/Bundle/Application/B320C8CF-5711-4F14-92C4-0693420DDE07/MyApp.app/MyApp Identifier: com.MyApp.release Version: 10.0.1 (1) AppStoreTools: 16A242b AppVariant: 1:iPhone16,2:18 Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] Coalition: com.MyApp.release [989] Date/Time: 2024-09-21 06:30:38.3210 -0500 Launch Time: 2024-09-21 06:18:03.0691 -0500 OS Version: iPhone OS 18.1 (22B5007p) Release Type: Beta Baseband Version: 2.15.01 Report Version: 104 Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000004 Exception Codes: 0x0000000000000001, 0x0000000000000004 VM Region Info: 0x4 is not in any region. Bytes before following region: 4340908028 REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL UNUSED SPACE AT START ---> __TEXT 102bd0000-102be0000 [ 64K] r-x/r-x SM=COW /var/containers/Bundle/Application/B320C8CF-5711-4F14-92C4-0693420DDE07/MyApp.app/MyApp Termination Reason: SIGNAL 11 Segmentation fault: 11 Terminating Process: exc handler [866] Triggered by Thread: 3 Thread 3 Crashed: 0 MyApp 0x0000000103b00b8c withTaskCancellationHandler<A>(operation:onCancel:isolation:) + 108 (/<compiler-generated>:0) 1 MyApp 0x0000000103b0284d closure #1 in DataRequest.dataTask<A>(automaticallyCancelling:forResponse:) + 1 (Concurrency.swift:352) 2 MyApp 0x0000000102f66011 partial apply for closure #1 in closure #1 in variable initialization expression of static FireAndForgetKey.liveValue + 1 3 MyApp 0x0000000102f80841 closure #1 in DataTask.response.getter + 1 4 MyApp 0x0000000102f66011 partial apply for closure #1 in closure #1 in variable initialization expression of static FireAndForgetKey.liveValue + 1 5 libswift_Concurrency.dylib 0x000000019164e689 completeTaskWithClosure(swift::AsyncContext*, swift::SwiftError*) + 1 (Task.cpp:471)
4
0
1.2k
Sep ’24
What's the correct way to check for unavailable API?
I ran into a problem recently with my production app and an update for iOS 18. In this example I was using a new API added to the RC candidate of iOS 18.0, using this API as an example, I couldn't find a satisfactory way to avoid crashing on iOS 18.1 where the API was not available. I had plenty of users running the iOS 18.1 Beta and ultimately it's my fault if a version of my app did work, and then didn't after an update.... This code causes a crash on iOS 18.1 beta as the .appleSleepingBreathingDisturbances API doesn't seem to have made it's way into the beta: if #available(iOS 18.0, *), #available(watchOS 11, *) { healthKitTypesToRead.insert(HKQuantityType.quantityType(forIdentifier: .appleSleepingBreathingDisturbances)!) } I tried this but it still crashed on 18.1: if #available(iOS 18.0, *), #available(watchOS 11, *) { if let newQuantity = HKQuantityType.quantityType(forIdentifier: .appleSleepingBreathingDisturbances) { healthKitTypesToRead.insert(newQuantity) } } In the end the only way I could resolve this was the following: if #available(iOS 18.1, *){ // Do nothing } else if #available(iOS 18.0, *), #available(watchOS 11, *) { if let newQuantity = HKQuantityType.quantityType(forIdentifier: .appleSleepingBreathingDisturbances) { healthKitTypesToRead.insert(newQuantity) } } This seems like a poor solution and I'll have to ensure I release a new version of the app once iOS 18.1 has the available API added to enable support for the feature. How could I have checked availability for this API correctly without causing the app to crash? I'm asking this question more as a Swift language feature rather than issue with the specific API as I'm sure that will get resolved soon anyway. Thanks
4
1
547
Sep ’24
Failed to build module 'CustomSDK'; SDK not supported by compiler due to Swift version mismatch on Xcode 16 Beta 6
I’m facing an issue while compiling a project with a CustomSDK on Xcode 16.0 Beta 6. The following error is displayed during the build process: Failed to build module 'CustomSDK'; this SDK is not supported by the compiler (the SDK is built with 'Apple Swift version 5.9 (swiftlang-5.9.0.128.108 clang-1500.0.40.1)', while this compiler is 'Apple Swift version 6.0 effective-5.10 (swiftlang-6.0.0.9.10 clang-1600.0.26.2)'). Please select a toolchain which matches the SDK. Steps I have taken so far: Set the BUILD_LIBRARY_FOR_DISTRIBUTION build setting to YES in the post_install script to ensure forward compatibility. Cleaned the project and deleted Derived Data. Verified that the latest SDK version was compiled using Swift 5 in Xcode 15.2, which should ensure compatibility with future versions. Tried re-adding the SDK pod and rebuilt the project. Despite these steps, the issue persists on Xcode 16 Beta 6. I suspect the problem could be related to a beta version of Xcode and compatibility issues, but I need guidance on how to ensure the SDK works with Xcode 16. Is this a known issue with Swift versioning in the beta release? Are there any workarounds or specific changes I should apply to make the SDK work with Xcode 16 Beta 6? Any help or suggestions would be appreciated!
6
1
1.7k
Sep ’24
unable to mutate struct var
I am not having any luck mutating a var in a structure, and yes, the method is defined as 'mutating' here's the struct definition: struct OnboardingSwipeableView: View{ static var shared = OnboardingSwipeableView() @State var currentPage = 0 var lock = NSLock() <snip> here's the method: mutating func goToNextPage(){ currentPage = self.currentPage+1 print("OBM->goToNestPage: currentPage=\(self.currentPage)") } however currentPage is not being updated. What gives?
1
0
195
Sep ’24