Dive into the world of programming languages used for app development.

All subtopics

Post

Replies

Boosts

Views

Activity

C++
Hi To All. I have recently started a course that will teach me how to use C++ coding, so I can improve my career prospects. I have come across an obstacle when it comes to downloading a programming tool and that is, they are not compatible with Sequoia 1.15.1. This includes Xcode, Clion, Codelite and Vs, I am at a crossroads in my decision making on how to overcome this problem please. Can someone help withme with a solution please. Thank you.
2
0
290
Oct ’24
Undefined symbols for architecture x86_64:
I am developing a simple camera JNI interface program in Objc. I managed to compile. But I get the following link error. I use the following command. Is there anything I can add to solve this problem? Note that I use Intel MacMini. g++ -framework Foundation -framework AVFoundation CameraMacOS.m Undefined symbols for architecture x86_64: "_CMVideoFormatDescriptionGetDimensions", referenced from: _openCamera in CameraMacOS-517c44.o _listWebcamNamesAndSizes in CameraMacOS-517c44.o "_CVPixelBufferGetBaseAddress", referenced from: -[CaptureDelegate captureOutput:didFinishProcessingPhoto:error:] in CameraMacOS-517c44.o "_CVPixelBufferGetBytesPerRow", referenced from: -[CaptureDelegate captureOutput:didFinishProcessingPhoto:error:] in CameraMacOS-517c44.o "_CVPixelBufferGetHeight", referenced from: -[CaptureDelegate captureOutput:didFinishProcessingPhoto:error:] in CameraMacOS-517c44.o "_CVPixelBufferGetWidth", referenced from: -[CaptureDelegate captureOutput:didFinishProcessingPhoto:error:] in CameraMacOS-517c44.o "_CVPixelBufferLockBaseAddress", referenced from: -[CaptureDelegate captureOutput:didFinishProcessingPhoto:error:] in CameraMacOS-517c44.o "_CVPixelBufferUnlockBaseAddress", referenced from: -[CaptureDelegate captureOutput:didFinishProcessingPhoto:error:] in CameraMacOS-517c44.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)
2
0
307
Oct ’24
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 leak and a crash when swizzling NSURLRequest initialiser
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?
3
0
274
Oct ’24
Applescript text item delimiters not working
I have a string of the form “Mon 22nd April”. I’m trying to extract the day (i.e. Mon), the date (i.e. 22nd) and the month (i.e. April) using this Applescript: set originalDateString to “Mon 22nd April” -- Extract the components by splitting the string set AppleScript's text item delimiters to " " set dayOfWeekAbbrev to text item 1 of originalDateString set dayOfMonth to text item 2 of originalDateString set monthName to text item 3 of originalDateString When I run this on its own it works as expected: dayOfWeekAbbrev is set to “Mon” dayOfMonth is set to “22nd” monthName is set to “April” When I run this inside a bigger script involving Numbers, the text item delimiters fails to work, no compile or run time errors occur and I end up with: dayOfWeekAbbrev is set to “M” dayOfMonth is set to “o” monthName is set to “n” I.e the first three characters of the string. If I replace originalDateString with the literal string “Mon 22nd April” I get the same result. In other words, text items and being recognized as individual characters, no delimiter (or delimiter is null). Totally confused.
5
0
349
Oct ’24
Application doesn't start: Namespace DYLD, Code 1 Library missing
I have a multi-platform application made with Delphi which uses FTDI D2XX drivers. All is well in other platforms but i have this issue in MacOS when i try to start the application: Termination Reason: Namespace DYLD, Code 1 Library missing Library not loaded: libftd2xx.dylib Referenced from: <CD2148C0-F76F-35D5-8E65-2BE51F201302> /Users/USER/*/USB_Editor.app/Contents/MacOS/USB_Editor Reason: tried: 'libftd2xx.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OSlibftd2xx.dylib' (no such file), 'libftd2xx.dylib' (no such file), '//libftd2xx.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS//libftd2xx.dylib' (no such file), '//libftd2xx.dylib' (no such file) (terminated at launch; ignore backtrace) If i try to run the executable i get a similar error which includes the users/user folder in the paths specified above. So if i copy libftd2xx.dylib to users/user the app can start from the executable and the USB library works well. The library is bundled in Contents/Framework as this seems to be the best (or only) accepted practice. Btw the app only starts during deployment if the library is found in Contents/MacOS. Library version is the most recent from FTDI site for the ARM architecture and followed their instructions to install. If i try the otool command on the library i get this: otool -L libftd2xx.dylib libftd2xx.dylib: libftd2xx.dylib (compatibility version 1.1.0, current version 1.4.30) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1336.61.1) /usr/lib/libobjc.A.dylib (compatibility version 1.0.0, current version 228.0.0) /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit (compatibility version 1.0.0, current version 275.0.0) /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation (compatibility version 150.0.0, current version 2202.0.0) I'm a Mac user since last week so my knowledge of the system is not so good yet (:
2
0
294
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
295
Oct ’24
Flutter barcode_scan2: ^4.3.3 non funziona bene su iOS
Stiamo sviluppando una App per iOS con Flutter, usiamo: Flutter barcode_scan2: ^4.3.3. Gli smartphone iOS cercano di riconoscere il tipo di codice a barre letto. Se il sistema crede che il codice sia gtin13 ma le cifre risultano 12, aggiunge uno zero iniziale. Come potremmo risolvere ? Grazie Settore sviluppo App Firenze Web Division
1
0
224
Oct ’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
252
Oct ’24
Crash with Progress type, Swift 6, iOS 18
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 () -&gt; () at &lt;compiler-generated&gt;: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.
23
7
933
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
360
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
524
Oct ’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
293
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
566
Oct ’24
How to use Xcode's provided tkinter module ?
Hi there, I’m having issue with the python3 installation provided by Xcode’s toolchain. I’m currently writing a LLDB plugin, using the LLDB python API, to allow the user to visualize audio data from the current debugged program in a GUI, using tkinter and matplotlib. I'm using those because I'm developing a cross-platform plugin, as I'm initially a Linux developer who wants to make this available to my fellow Apple audio devs. My issue arise at least on two setups MacOS 12.7.6 Monterey with Xcode 14.2 MacOS 14 with Xcode 15.4 (not my machine) Because I wanna support Xcode’s toolchain, I want to use Xcode’s lldb. Xcode’s lldb uses Xcode’s provided python, which I’m having issues with when loading tkinter.The issue can be reproduced like this : > xcrun python3 -c "import tkinter;tkinter._test()" macOS 12 (1207) or later required, have instead 12 (1206) ! zsh: abort xcrun python3 -c "import tkinter;tkinter._test()" On MacOS 14 the version numbers are : macOS 14 (1407) or later required, have instead 14 (1406) ! You can see it fails to load tkinter. From what I understood so far, it looks like the tkinter/tcl/tk version distributed with Xcode is not supported by MacOS ?I checked and the imported tkinter module is definitely the one provided by Xcode’s toolchain : # Checking where tkinter is installed > fd "^tkinter$" /Applications/Xcode.app /Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/tkinter/ /Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/tkinter/ /Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/site-packages/future/moves/tkinter/ # Checking that Xcode python uses the right module - it matches > xcrun python3 -c "import tkinter;print(tkinter.sys.modules['tkinter'])" <module 'tkinter' from '/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py'> I can get a working tkinter working by installing it using homebrew or macports, but I’m not able to use it with Xcode’s python installation. I tried overwriting sys.path to force Xcode’s python to import homebrew’s tkinter module, but it still loads Xcode’s tkinter .so. In the crash report I can see it indeed loads tcl/tk 8.5 and loads _tkinter.cpython-39-darwin.so from Xcode. I could disable the SIP (System Integrity Protection) to force to load another version of the library, but that wouldn’t be something I can ask the users. On the LLDB forum, they advise against using another python interpreter that the one provided by the toolchain. So is there a way to get the provided tkinter/tcl/tk installation to work ? If not I’m confused about why it’s provided in the first place. Thanks a lot for your time and please tell me if you have any questions. PS: if possible i'll post the head of the crash report in the comment of this post
5
1
798
Sep ’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
327
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
436
Sep ’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
MPMediaItemPropertyArtwork crashes on Swift 6
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
6
0
492
Sep ’24