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

All subtopics

Post

Replies

Boosts

Views

Activity

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
553
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
198
Sep ’24
Xcode 16 beta 6 - unexpected concurrency build issues
The following behavior seems like a bug in the swift compiler that ships with Xcode 16 beta 6. Add the following code snippet to a new iOS app project using Xcode 16 beta 6 and observe the error an warning called out in the comments within the itemProvider() method: import WebKit extension WKWebView { func allowInspectionForDebugBuilds() { // commenting out the following line makes it so that the completion closure argument of the trailing closure // passed to NSItemProvider.registerDataRepresentation(forTypeIdentifier:visibility:loadHandler:) is no longer // isolated to the main actor, thus resolving the build issues. It is unexpected that the presence or absence of // the following line would have this kind of impact. isInspectable = true } } class Foo { func itemProvider() -> NSItemProvider? { let itemProvider = NSItemProvider() itemProvider.registerDataRepresentation(forTypeIdentifier: "", visibility: .all) { completion in Task.detached { guard let url = URL(string: "") else { completion(nil, NSError()) // error: Expression is 'async' but is not marked with 'await' return } let task = URLSession.shared.dataTask(with: url) { data, _, error in completion(data, error) // warning: Call to main actor-isolated parameter 'completion' in a synchronous nonisolated context; this is an error in the Swift 6 language mode } task.resume() } return Progress() } return itemProvider } } Now, comment out the line isInspectable = true and observe that the error and warning disappear. Also filed as FB14783405 and https://github.com/swiftlang/swift/issues/76171 Hoping to see this fixed before Xcode 16 stable.
8
0
698
Aug ’24
Swift 6 Migration error in Sample code (Updating an app to use strict concurrency sample code) provided by Apple.
Updating an app to use strict concurrency is not compiling in Swift 6 with strict concurrency enabled. I am getting the following error in Xcode Version 16.0 (16A242d). private func queryHealthKit() async throws -&gt; ( [HKSample]?, [HKDeletedObject]?, HKQueryAnchor? ) { try await withCheckedThrowingContinuation { continuation in // Create a predicate that returns only samples created within the last 24 hours. let endDate = Date() let startDate = endDate.addingTimeInterval(-24.0 * 60.0 * 60.0) let datePredicate = HKQuery.predicateForSamples( withStart: startDate, end: endDate, options: [.strictStartDate, .strictEndDate]) // Create the query. let query = HKAnchoredObjectQuery( type: caffeineType, predicate: datePredicate, anchor: anchor, limit: HKObjectQueryNoLimit ) { (_, samples, deletedSamples, newAnchor, error) in // When the query ends, check for errors. if let error { continuation.resume(throwing: error) } else { continuation.resume(returning: (samples, deletedSamples, newAnchor)) } } store.execute(query) } } The error is on ** continuation.resume(returning: (samples, deletedSamples, newAnchor)) ** and the error is Task-isolated value of type '([HKSample]?, [HKDeletedObject]?, HKQueryAnchor?)' passed as a strongly transferred parameter; later accesses could race. How to solve this error?
2
1
670
Sep ’24
How to fix this Swift 6 migration issue?
Here is a code snippet about AVPlayer. avPlayer.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 60), queue: .main) { [weak self] _ in // Call main actor-isolated instance methods } Xcode shows warnings that Call to main actor-isolated instance method '***' in a synchronous nonisolated context; this is an error in the Swift 6 language mode. How can I fix this? avPlayer.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 60), queue: .main) { [weak self] _ in Task { @MainActor in // Call main actor-isolated instance methods } } Can I use this solution above? But it seems switching actors frequently can slow down performance.
1
0
894
Sep ’24
"Undefined symbol: __swift_FORCE_LOAD_$_swiftCompatibility56" or "Symbol not found: (_objc_claimAutoreleasedReturnValue)"
I'm working on a Payment SDK integrating Storekit2 for Unity games. The workflow is as follows: build the swift project that exposes objective c interface to static libraries, then archive them into xcframework embed the xcframework into native unity plugin where we call objective-c functions from C# export the unity project to Xcode project build the game Xcode project When deployment target of swift project is set to iOS15 No matter what iOS version target is set in the game Xcode project, I got build error: Undefined symbol: __swift_FORCE_LOAD_$_swiftCompatibility56 When deployment target of swift project is set to iOS16 And set the deployment target of game project to iOS15 (I need to let the payment sdk to work on iOS15 as Storekit2 and swift concurrency shipped with iOS15). I can build the game Xcode project, and it works on iOS16+ device. But when I run on iOS15 device, I got runtime error: 2024-08-26 18:17:29.289078+0900 ***[1404:95780] Error loading /var/containers/Bundle/Application/123/***/Frameworks/UnityFramework.framework/UnityFramework: dlopen(/var/containers/Bundle/Application/123/***/Frameworks/UnityFramework.framework/UnityFramework, 0x0109): Symbol not found: (_objc_claimAutoreleasedReturnValue) Referenced from: '/private/var/containers/Bundle/Application/123/***/Frameworks/UnityFramework.framework/UnityFramework' Expected in: '/usr/lib/libobjc.A.dylib' 2024-08-26 18:17:29.418604+0900 ***[1404:95780] Error loading /var/containers/Bundle/Application/123/***/Frameworks/UnityFramework.framework/UnityFramework: dlopen(/var/containers/Bundle/Application/123/***/Frameworks/UnityFramework.framework/UnityFramework, 0x0109): Symbol not found: (_objc_claimAutoreleasedReturnValue) Referenced from: '/private/var/containers/Bundle/Application/123/***/Frameworks/UnityFramework.framework/UnityFramework' Expected in: '/usr/lib/libobjc.A.dylib' If I chose not to build framework into static libraries but dynamic ones, I can avoid this problem but Unity cannot handle dynamic libraries well when exporting to Xcode project so I have no choice here but to stick to static ones. minimum reproduction I made a minimum reproduction project to exclude the process of unity. a fresh new empty objective-c app project embed the xcframework built with target iOS15 call a function in the framework in applicationDidFinishLaunch set the deployment target of main target of the app project to iOS15. build the project I still get Undefined symbol: __swift_FORCE_LOAD_$_swiftCompatibility56 versions Xcode version 15.4 Test iOS device version 15.8
7
0
987
Aug ’24
withCheckedContinuation crashes on Xcode 16
We are using a 3rd party SDK which crashes on iOS 18 in certain scenarios. They say they need Apple to fix this bug ahead of release https://github.com/swiftlang/swift/issues/75952 but I'm skeptical since it is only a few weeks away most likely. The bug seems pretty bad so is there any chance it will be fixed before iOS 18? We aim for a same-day release so would be great to know if we need to remove the 3rd party SDK or not.
5
1
1.5k
Aug ’24
Passing C++ Types as Reference using SWIFT_IMMORTAL_REFERENCE.
I have a Class defined in C++, I want to pass the instance of class from C++ to Swift as a reference type. By default swift maps C++ classes as value types but we can change this behavior by using SWIFT_IMMORTAL_REFERENCE annotation mentioned here. The example mentioned here is of Singelton class but I have a usecase where i require more than one instance. Cpp Class Skeleton. class Cpp { public: void Print () noexcept; void SetValue (int pValue) noexcept; // Method which is Invoked by Swift. static Cpp& ReturnObj () noexcept; private: int vValue; } SWIFT_IMMORTAL_REFERENCE; Definition of Return Obj Cpp& Cpp::ReturnObj () noexcept { static Cpp obj; return obj; } Swift Co var obj : Cpp = Cpp.ReturnObj() withUnsafeBytes(of: &obj) {(pointer : UnsafeRawBufferPointer) in print (pointer) print (pointer.baseAddress!) } Output Address Printed by C++ 0x100008000 Address Printed by Swift 0x00007ff7bfeff108 So from the above observation copy is passed. How to do pass by reference then?
2
0
435
Sep ’24
Passing User Defined Swift Structure to C++ using In Param
I have a Usecase where I want to pass user-defined swift structure instance from Swift to C++ as argument to the C++ Function. In the documentation it's mentioned that swift exposes these structures to c++. Swift Structure. public struct MyStruct { public init (_ pValue : Int) { uValue = pValue } public var uValue : Int } I am able to Create Instance in C++ . Code void CppClass::CreateSwiftStruct () { Interop::MyStruct my_struct = Interop::MyStruct::init (20); } But when I define a C++ Function which takes Interop::MyStruct as argument then that function doesn't get exposed to swift, so i am not able to call it. Skeleton For CppClass class CppClass { static void PassStruct (Interop::MyStruct pStruct); static void Test (); } Here PassStruct Method doesn't get exposed to C++ but Test does. How can I pass Struct Instance in swift to C++ Function as In Param?
1
0
330
Sep ’24
Returning Typed Pointer From Swift to C++
I have a struct defined in Swift, i want to pass it's instance pointer from swift to C++. When I am trying to directly return Typed Pointer from Swift Function to C++, the function doesn't get expose to C++. Code which i have tried. // Defined Structure public struct MyStruct { public init (_ pValue : Int) { uValue = pValue } public var uValue : Int } var my_struct = MyStruct(20) // Function which returns Struct Pointer to C++ // When I return typed pointer this function doesn't get exposed to C++ public func PassStructPointer () -> UnsafeMutablePointer<MyStruct> { withUnsafeMutablePointer(to: &my_struct) { pointer in return pointer } } But when I pass UnsafeRawMutablePointer instead of type pointer then the function does get expose to C++ var my_struct = MyStruct(20) // This get expose to C++. public func PassStructPointer () -> UnsafeMutableRawPointer { return withUnsafeMutableBytes(of: &my_struct) { pointer in return pointer.baseAddress! } } Can we not pass typed pointer of the types defined by us?
2
0
305
Sep ’24
UnsafeMutablePointer direct exposure.
I am trying to use the swift type UnsafeMutablePointer directly in C++. According to the documentation mentioned, swift expose this type to C++. But I am not able to use it . void GetPointerFromSwift () { // Calls a swift function to get a pointer. swift::UnsafeMutablePointer<swit::Int> x = Interop::GetPointer () }
7
0
364
Sep ’24
Local push, sending custom data like APN
Hello, I'm doing some test and I dowload the sample from here https://developer.apple.com/documentation/networkextension/local_push_connectivity/receiving_voice_and_text_communications_on_a_local_network Everything works correctly and the phones are able to exchange messages without problems and the server sends pushes to the devices. Now I would like to modify the server so that, when it sends the push to the mobile device, it can change the sound or add other information as is possible when using APN. Now I would like to modify the server so that, when it sends the push to the mobile device, it can change the sound or add other information as is possible when using APN. Is there any way to send a payload like for APN? Thank's Omar
1
0
319
Sep ’24
Python vs Swift for macOS CLI tool?
We have an in-house CLI tool built entirely in Python to help us with OS-level workflows. It’s been excellent, but we’re encountering some growing pains. We’ve encountered a case where we’d like to use Apple’s Authorization Plugin, which we can’t directly utilize in Python. Since I doubt this’ll be the last time we encounter Swift or Obj-C specific tools, I’m starting to wonder if a total rewrite into Swift might be in order. Alternatives include writing a wrapper in Swift just for the Auth Plugin, exposing an API that we’ll consume in Python. Since this will only ever be a macOS, tool, I’m starting to feel like going with Python was a dumb idea in the first place. Would love to know what you guys think. p.s. I was advised to post my question on these forums in hopes of being graced by the Apple god Quinn, “The Eskimo”.
2
0
322
Sep ’24