Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

UIViewRepresentable is not working
I have been trying to integrate a UIKit view into SwiftUI, specifically a WKWebView. However, I keep encountering a does not conform to protocol error. Here's my code: import SwiftUI import WebKit struct SimpleWebView: View { var body: some View { WebViewContainerRepresentable() .edgesIgnoringSafeArea(.all) } } struct WebViewContainerRepresentable: UIViewRepresentable { typealias UIViewType = WKWebView func makeUIView(context: Context) -> WKWebView { let webView = WKWebView() if let url = Bundle.main.url(forResource: "index", withExtension: "html") { webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent()) } return webView } func updateUIView(_ uiView: WKWebView, context: Context) { // Updates not required for this use case } } I tried this with other views as well, and it turns out this is not WKWebView-specific. The minimum deployment version is iOS 15. Any help would be much appreciated. Let me know if I need to add any more information.
1
0
403
Dec ’24
Get CloudKit records created by specific user
I've been searching all over the web trying to find the proper way to get all records created by a specific user in CloudKit. I am able to get the correct id using: guard let userRecordID = try? await container.userRecordID() else { return } I can see that the id returned is associated with records in my CloudKit dashboard. So I would expect that the following would get those records: let predicate = NSPredicate(format: "%K == %@", #keyPath(CKRecord.creatorUserRecordID), userRecordID) let query = CKQuery(recordType: "CKUser", predicate: predicate) But instead when I use that query it returns nothing. It is successful but with nothing returned... Any ideas why this would be happening? P.S. I have also tried constructing the predicate using the reference, but I get the same result - success with no results. P.S.2 Also worth mentioning that I am trying to get the results from the public database and I have set my CKContainer to the correct container id.
5
0
751
Dec ’24
Decryption failure - Migrated from Objective-C to Swift (AES256 Decryption failure in swift language)
Decrypting Data to String Conversion failure Development environment: Xcode 15.4, macOS 14.7 Run-time configuration: iOS 15.8.1 & 16.0.1 DESCRIPTION OF PROBLEM We were using objective C implementation of CCCrypt(see below) in our app earlier which we migrated to swift implementation recently. We convert the byte array that CCCrypt returns into Data, and data to string to read the decrypted value. It works perfectly fine in Objective C, whereas with new swift implementation this conversion is failing, it looks like CCCrypt is returning byte array with few non UTF8 characters and that conversion is failing in swift since Objective C is more tolerant with this conversion and converts the byte array to Data and then to string even though there are few imperfect UTF characters in the array. Objective C CCCryptorStatus CCCrypt( CCOperation op, /* kCCEncrypt, etc. / CCAlgorithm alg, / kCCAlgorithmAES128, etc. / CCOptions options, / kCCOptionPKCS7Padding, etc. */ const void *key, size_t keyLength, const void iv, / optional initialization vector */ const void dataIn, / optional per op and alg */ size_t dataInLength, void dataOut, / data RETURNED here */ size_t dataOutAvailable, size_t *dataOutMoved) API_AVAILABLE(macos(10.4), ios(2.0)); Swift Code CCCrypt(_ op: CCOperation, _ alg: CCAlgorithm, _ options: CCOptions, _ key: UnsafeRawPointer!, _ keyLength: Int, _ iv: UnsafeRawPointer!, _ dataIn: UnsafeRawPointer!, _ dataInLength: Int, _ dataOut: UnsafeMutableRawPointer!, _ dataOutAvailable: Int, _ dataOutMoved: UnsafeMutablePointer!) -> CCCryptorStatus Data to String Conversion String(data: decryptedData, encoding: .utf8) STEPS TO REPRODUCE Able to reproduce on below devices iPhone - 7 OS Version 15.8.1 iPhone 14- Pro OS Version 16.0.2 iPhone 15 iOS 18.0.1 **Decryption method return "Data" and converting into string using ".utf8" but String conversion is failing on above devices and some other devices as well. Decryption failure not occurring always. ** Below code used for String conversion String(data: decryptedData, encoding: .utf8)
0
0
214
Dec ’24
libswiftNetwork.dylib randomly crashed on iOS 16
My application crash on iOS 16 randomly, stack trace like this: libswiftCore.dylib __swift_release_dealloc + 32 libswiftNetwork.dylib outlined consume of (@escaping @callee_guaranteed (@in_guaranteed Network.NWConnection.State) -> ())? + 52 libswiftNetwork.dylib outlined consume of (@escaping @callee_guaranteed (@in_guaranteed Network.NWConnection.State) -> ())? + 52 libswiftCore.dylib __swift_release_dealloc + 56 libsystem_blocks.dylib __call_dispose_helpers_excp + 48 libsystem_blocks.dylib __Block_release + 252 libsystem_blocks.dylib bool HelperBase::disposeCapture<(HelperBase::BlockCaptureKind)4>(unsigned int, unsigned char*) + 68 libsystem_blocks.dylib HelperBase::destroyBlock(Block_layout*, bool, unsigned char*) + 180 libsystem_blocks.dylib __call_dispose_helpers_excp + 72 libsystem_blocks.dylib __Block_release + 252 libdispatch.dylib ___destroy_helper_block_8_32c35typeinfo name for dispatch_block_private_data_s + 96 libsystem_blocks.dylib __call_dispose_helpers_excp + 48 libsystem_blocks.dylib __Block_release + 252 libdispatch.dylib __dispatch_client_callout + 20 libdispatch.dylib __dispatch_root_queue_drain + 684 libdispatch.dylib __dispatch_worker_thread2 + 164 libsystem_pthread.dylib __pthread_wqthread + 228 From buly(a tool to report crash) we notice that this crash only happens on iOS 16
1
0
246
Dec ’24
array
I'm using xcode 16.1 withSwift. I want to know how to call a function passing in an array. Also I need to know how to declare the function receiving the array. I currently have: func myfunc(costa: [Double]) { } I call it like this: myfunc(costa:[ ]) It's an array of Doubles. I don't get any errors but the array is always empty. Please help. Thank you.
3
0
246
Dec ’24
Trying to understand Swift-C++ interopability
Hi, I'm struggling to understand using Swift-C++ in the same project. I have an existing code-base that makes heavy use of Swift-Objective-C interoperability. We make use of swift classes in our project. When I enable swift-objective c interoperability I am running into numerous build errors in the generated bridging header. I'm trying to understand why these errors exist and what to do to get around them. I have a project that I've set up with some test code, and I'm running into an error here: public class Foo { let name: String public init(name: String) { self.name = name } } public class Bar { let name: String public init(name : String) { self.name = name; } public func getFoo() -> Foo { return Foo(name: self.name); } } In the header file: Unknown type name 'Foo' SWIFT_INLINE_THUNK Foo getFoo() SWIFT_SYMBOL("s:13ForestBuilder3BarC6getFooAA0E0CyF"); This error goes away if I use structs, but for the purposes of porting my codebase, I'd prefer to use classes. Do classes not play nice here? Or am I misunderstanding something. Thanks.
0
0
340
Dec ’24
percentages
I want to know how to format doubles. In the program I have 4.3333 I just want to print 4 to the screen. I just want to print whole numbers. I'm using Swiftui with xcode. Please help. Thank you.
3
0
235
Dec ’24
Passkey Creation SDK does not return Timeout Error on FaceID authentication times out.
We would like to show a user-friendly message but can not. Description: When attempting to create a duplicate passkey using the ASAuthrorizationController in iOS, the Face ID authentication times out SDK does not return a timeout specific error. Instead, it directly returns an error stating that duplicate passkey cannot be created. SDK to first handle the FaceID timeout case and provide a distinct timeout error so we can gracefully manage this scenario before the duplicate passkey validation occurs. Steps to Reproduce: Implement passkey creation flow using ASAuthorizationController. Attempt to register a duplicate passkey (e.g., using the same user ID and challenge). Let FaceID prompt timeout (do not interact with the authentication prompt).
0
0
200
Dec ’24
Common blocks in Swift?
I am porting an old app from ObjC. The app uses many defined constants such as: #define COM_OFFSET 12.5 and many variables that are read and/or written throughout the App, such as: PCDate* Dates[367]; @class PCMainView; PCMainView* MainView; in one file called "PCCommon.h" How do I duplicate this function in Swift? I have looked around and have found no help. Thanks in advance.
1
0
369
Dec ’24
App Rejected: Non-Public Symbols _lzma_code and _lzma_end in Payload/Hogs.app/Hogs
Hello, I have integrated LZMA2 compression into my iOS app, Hogs, and successfully implemented compression. However, when attempting to upload the app for TestFlight, I encountered an error: "The app references non-public symbols in Payload/Hogs.app/Hogs: _lzma_code, _lzma_end." These functions are part of the LZMA compression library (specifically LZMA2). Here's a detailed description of the issue: What I Have Done: LZMA2 Integration: I integrated LZMA2 compression into the app and created a wrapper around the LZMA functions (_lzma_code, _lzma_end) to prevent direct references. App Build Configuration: I ensured the LZMA2 library is linked correctly with the -lzma flag in the linker settings. I wrapped the LZMA functions in custom functions (my_lzma_code, my_lzma_end) in an attempt to avoid using the non-public symbols directly. Error Message: During the app submission process, I received the following error: "The app references non-public symbols in Payload/Hogs.app/Hogs: _lzma_code, _lzma_end." Steps Taken to Resolve: Checked if any LZMA functions were exposed incorrectly. Ensured that all non-public symbols were properly encapsulated in a wrapper. Verified linker settings to ensure the proper inclusion of the LZMA2 library. Request: Could anyone provide suggestions or best practices to resolve this issue and avoid references to non-public symbols? Should I use a different method for linking LZMA2 or encapsulating these symbols? Thank You: I appreciate your help in resolving this issue so I can move forward with submitting the app for TestFlight.
1
0
290
Dec ’24
App Rejected: Non-Public Symbols _lzma_code and _lzma_end in Payload/Hogs.app/Hogs
I recently submitted my app, Hogs, to the App Store, but it was rejected due to references to non-public symbols: _lzma_code _lzma_end I am using the LZMA compression library in my app, and these functions are part of that implementation. Here's a breakdown of my usage: Library Used: liblzma (custom wrapper around LZMA functions) Error Message: "The app references non-public symbols in Payload/Hogs.app/Hogs: _lzma_code, _lzma_end." Steps I’ve Taken: I’ve wrapped the LZMA functions in my own functions (my_lzma_code, my_lzma_end) to prevent direct references. I have checked the build settings and included -lzma in the linker flags. I’ve tried using a custom framework to encapsulate LZMA, but the issue persists. I would greatly appreciate any help or suggestions on how to resolve this issue and get my app approved. Is there any workaround or adjustment I can make to avoid using these non-public symbols? Thank you in advance for your assistance.
1
0
247
Dec ’24
SwiftUI Entry Point - Proper Location In Project
Hi In C#, one can define associated functions by the following. Notice that "Declarations DE" is a reference to a function in another C# project file. This lets the compiler know that there are other references in the project. Likewise, "Form_Load" is the entry point of the code, similar to "main" in C. Any calls to related functions can be made in this section, to the functions that have been previously defined above. So I set out trying to find similar information about SwiftUI, and found several, but only offer partial answers to my questions. The YouTube video... Extracting functions and subviews in SwiftUI | Bootcamp #20 - YouTube ... goes into some of the details, but still leaves me hanging. Likewise... SOLVED: Swift Functions In Swift UI – SwiftUI – Hacking with Swift forums ... has further information, but nothing concrete that I am looking for. Now in the SwiftUI project, I tried this... The most confusing thing for me, is where is "main"? I found several examples that call functions from the structure shown above, BUT I have no reason as to why. So one web example on StackOverFlow called the function from position 1. That did not work. Position 2 worked to call the function at position 3, but really, why? All this activity brings up a lot of questions for me, such as: Does SwiftUI need function callouts similar to C#, and they are called out even before running "main". I seem to recall Borland Delphi being this way as well. How does SwiftUI make references to other classes (places where other functions are stored in separate files)? Does SwiftUI actually make use of "main" in the normal sense, i.e. similar to C, C#, Rust and so on? I did notice that once a SwiftUI function is called, it makes reference to data being passed very similar to other languages, at least for the examples I found. Note that I looked at official SwiftUI documentation, but did not come across information that answers the above.
6
0
445
Dec ’24
Struggling with async/await: Fetching an image off the main thread
Hey everyone, I’m learning async/await and trying to fetch an image from a URL off the main thread to avoid overloading it, while updating the UI afterward. Before starting the fetch, I want to show a loading indicator (UI-related work). I’ve implemented this in two different ways using Task and Task.detached, and I have some doubts: Is using Task { @MainActor the better approach? I added @MainActor because, after await, the resumed execution might not return to the Task's original actor. Is this the right way to ensure UI updates are done safely? Does calling fetchImage() on @MainActor force it to run entirely on the main thread? I used an async data fetch function (not explicitly marked with any actor). If I were to use a completion handler instead, would the function run on the main thread? Is using Task.detached overkill here? I tried Task.detached to ensure the fetch runs on a non-main actor. However, it seems to involve unnecessary actor hopping since I still need to hop back to the main actor for UI updates. Is there any scenario where Task.detached would be a better fit? class ViewController : UIViewController{ override func viewDidLoad() { super.viewDidLoad() //MARK: First approch Task{@MainActor in showLoading() let image = try? await fetchImage() //Will the image fetch happen on main thread? updateImageView(image:image) hideLoading() } //MARK: 2nd approch Task{@MainActor in showLoading() let detachedTask = Task.detached{ try await self.fetchImage() } updateImageView(image:try? await detachedTask.value) hideLoading() } } func fetchImage() async throws -> UIImage { let url = URL(string: "https://via.placeholder.com/600x400.png?text=Example+Image")! //Async data function call let (data, response) = try await URLSession.shared.data(from: url) guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { throw URLError(.badServerResponse) } guard let image = UIImage(data: data) else { throw URLError(.cannotDecodeContentData) } return image } func showLoading(){ //Show Loader handling } func hideLoading(){ //Hides the loader } func updateImageView(image:UIImage?){ //Image view updated } }
5
0
1k
Dec ’24
Swift playground
Hi, I want to create a dashboard in a app using swift playgrounds with esp 32 and a led. The dashboard should have a toggle switch to toggle the switch state like on/off for the led once i get the basics i want to create a full dashboards with things like gauges, sliders, button and many more. Can someone please help/guide me. Thanks.
0
0
266
Dec ’24
Overall Code Structure Of Swift Project
I was a long time C# programmer, and recently started learning Rust. Now that I recently purchased my first Mac, I ran into several issues trying to run binaries on the Mac, due to various restrictions. On another forum post here, it was mentioned that I should take a look at Swift, as a development tool. This comment brings up an entirely new topic for me, as I discovered that the Swift project file structure seems daunting. But first let's backtrack to when I used C#. C# The first graphic show the default file structure that I used to start a new C# project. I would copy this entire folder structure to the clipboard and paste it where my new project folder was located, and start coding. Using this same principle, I wrote my own music player, and again the file structure for the entire project was as below. For those that may not know, the "bin" folder contains both debug and release folders and appropriate contents. Swift I created a Windows UI called "Test" using Swift, and then started poking around the file system, trying to determine the file structure that was created. Unbeknownst to me at the time, part of the project files ended up on the Desktop in a folder called Test. I did not expect Swift to place the files there. When I click on the Test folder and look inside, I see a file with a "xcodeproj" extension, which makes sense to me, as this is similar to C#. What I don't see however, is any file labeled Test.App. I also don't see either debug or release folders for this project. Obviously there are additional files for this project that are "somewhere", just not in a location I am aware of.
7
0
689
Dec ’24
Causes of disordered dictionary in Swift
Everyone knows that dictionaries in swift are unordered collections, there is no problem with that. I've noticed some behavior that I can't explain and hope someone can help me. The first variant We have a very simple code: struct Test { let dict = [1: “1”, 2: “2”, 3: “3”, 4: “4”, 5: “5”] func test() { for i in dict { print(i) } } } If you call test() several times in a row, the output to the console on my computer looks something like this: (key: 5, value: “5”) (key: 1, value: “1”) (key: 2, value: “2”) (key: 3, value: “3”) (key: 4, value: “4”) (key: 2, value: “2”) (key: 3, value: “3”) (key: 1, value: “1”) (key: 4, value: “4”) (key: 5, value: “5”) (key: 1, value: “1”) (key: 3, value: “3”) (key: 2, value: “2”) (key: 5, value: “5”) (key: 4, value: “4”) At each new for loop we get a random order of elements It seemed logical to me, because a dictionary is an unordered collection and this is correct behavior. However The second variant the same code on my colleague's computer, but in the console we see something like this: (key: 2, value: “2”) (key: 3, value: “3”) (key: 1, value: “1”) (key: 4, value: “4”) (key: 5, value: “5”) (key: 2, value: “2”) (key: 3, value: “3”) (key: 1, value: “1”) (key: 4, value: “4”) (key: 5, value: “5”) (key: 2, value: “2”) (key: 3, value: “3”) (key: 1, value: “1”) (key: 4, value: “4”) (key: 5, value: “5”) always, within the same session, we get the same order in print(i) We didn't use Playground, within which there may be differences, but a real project. swift version 5+ we tested on Xcode 14+, 15+ (at first I thought it was because the first version had 14 and the second version had 15, but then a third colleague with Xcode 15 had the behavior from the first scenario) we did a lot of checks, several dozens of times and always got that on one computer random output of items to the console, and in another case disordered only in the first output to the console Thanks
4
0
358
Dec ’24
Upgrade old App to Swift 4
I have an old app that I just got a notice will be pulled form the App Store if I don't upgrade. I tried to open in Xcode but it says I need to use Xcode 10.1 to convert to Swift 4. Exact message - "Use Xcode 10.1 to migrate the code to Swift 4." I downloaded Xcode 10.1 , now the OS (Sequoia ) says can't do it, have to use the latest version of Xcode. Exact message - "The version of Xcode installed on this Mac is not compatible with macOS Sequoia. Download the latest version for free from the App Store." Any experience with this and suggestions would be greatly appreciated.
1
0
367
Dec ’24
TaskExecutor and Swift 6 question
I have the following TaskExecutor code in Swift 6 and is getting the following error: //Error Passing closure as a sending parameter risks causing data races between main actor-isolated code and concurrent execution of the closure. May I know what is the best way to approach this? This is the default code generated by Xcode when creating a Vision Pro App using Metal as the Immersive Renderer. Renderer @MainActor static func startRenderLoop(_ layerRenderer: LayerRenderer, appModel: AppModel) { Task(executorPreference: RendererTaskExecutor.shared) { //Error let renderer = Renderer(layerRenderer, appModel: appModel) await renderer.startARSession() await renderer.renderLoop() } } final class RendererTaskExecutor: TaskExecutor { private let queue = DispatchQueue(label: "RenderThreadQueue", qos: .userInteractive) func enqueue(_ job: UnownedJob) { queue.async { job.runSynchronously(on: self.asUnownedSerialExecutor()) } } func asUnownedSerialExecutor() -&gt; UnownedTaskExecutor { return UnownedTaskExecutor(ordinary: self) } static let shared: RendererTaskExecutor = RendererTaskExecutor() }
1
0
675
Dec ’24