Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Posts under Swift tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

NSTextAttachment lagging in textkit 2
I have an attributedString with 100 NSTextAttachments(contains image of 400kb). When i scroll the textview, it is lagging, When i did the same in textkit 1, it is butter smooth. It can be because of how textkit 1 & 2 layout the elements. let attachment = NSTextAttachment() attachment.image = UIImage(named: "image2") let attachmentString = NSAttributedString(attachment: attachment) let mutableAttributedString = NSMutableAttributedString(attributedString: textView.attributedText) for _ in 0...100 { mutableAttributedString.append(NSAttributedString(string: "\n")) mutableAttributedString.append(attachmentString) } textView.attributedText = mutableAttributedString How to handle images in textkit 2 so that it feels smooth while scrolling textview?
1
0
54
9h
Lazy cell registration causes crash while dequeue the collectionview cell in collectionview
Cell Registration lazy var headerCell: UICollectionView.SupplementaryRegistration<UICollectionReusableView> = .init(elementKind: UICollectionView.elementKindSectionHeader) { supplementaryView, elementKind, indexPath in } and Cell Dequeue datasource.supplementaryViewProvider = { [weak self] collectionView, kind, indexPath in return collectionView.dequeueConfiguredReusableSupplementary(using: headerCell, for: indexPath) } I am registering a collectionview cell or collwctionview reusable view as lazy variable. It causes a crash like Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Attempted to dequeue a supplementary view using a registration that was created inside -collectionView:viewForSupplementaryElementOfKind:atIndexPath: or inside a UICollectionViewDiffableDataSource supplementary view provider. Creating a new registration each time a supplementary view is requested will prevent reuse and cause created supplementary views to remain inaccessible in memory for the lifetime of the collection view. Registrations should be created up front and reused. Registration: <UICollectionViewSupplementaryRegistration: 0x600001798a00>
2
0
154
1d
Why Actor-isolated property cannot be passed 'inout' to 'async' function call?
Considering below dummy codes: @MainActor var globalNumber = 0 @MainActor func increase(_ number: inout Int) async { // some async code excluded number += 1 } class Dummy: @unchecked Sendable { @MainActor var number: Int { get { globalNumber } set { globalNumber = newValue } } @MainActor func change() async { await increase(&number) //Actor-isolated property 'number' cannot be passed 'inout' to 'async' function call } } I'm not really trying to make an increasing function like that, this is just an example to make everything happen. As for why number is a computed property, this is to trigger the actor-isolated condition (otherwise, if the property is stored and is a value type, this condition will not be triggered). Under these conditions, in function change(), I got the error: Actor-isolated property 'number' cannot be passed 'inout' to 'async' function call. My question is: Why Actor-isolated property cannot be passed 'inout' to 'async' function call? What is the purpose of this design? If this were allowed, what problems might it cause?
0
0
110
1d
Persistent View Failure After Saving Edits in SwiftUI iOS App
Hello Apple Developer Community, I’m facing a recurring issue in my SwiftUI iOS app where a specific view fails to reload correctly after saving edits and navigating back to it. The failure happens consistently post-save, and I’m looking for insights from the community. 🛠 App Overview Purpose A SwiftUI app that manages user-created data, including images, text fields, and completion tracking. Tech Stack: SwiftUI, Swift 5.x MSAL for authentication Azure Cosmos DB (NoSQL) for backend data Azure Blob Storage for images Environment: Xcode 15.x iOS 17 (tested on iOS 18.2 simulator and iPhone 16 Pro) User Context: Users authenticate via MSAL. Data is fetched via Azure Functions, stored in Cosmos DB, and displayed dynamically. 🚨 Issue Description 🔁 Steps to Reproduce Open a SwiftUI view (e.g., a dashboard displaying a user’s saved data). Edit an item (e.g., update a name, upload a new image, modify completion progress). Save changes via an API call (sendDataToBackend). The view navigates back, but the image URL loses its SAS token. Navigate away (e.g., back to the home screen or another tab). Return to the view. ❌ Result The view crashes, displays blank, or fails to load updated data. SwiftUI refreshes text-based data correctly, but AsyncImage does not. Printing the image URL post-save shows that the SAS token (?sv=...) is missing. ❓ Question How can I properly reload AsyncImage after saving, without losing the SAS token? 🛠 What I’ve Tried ✅ Verified JSON Structure Debugged pre- and post-save JSON. Confirmed field names match the Codable model. ✅ Forced SwiftUI to Refresh Tried .id(UUID()) on NavigationStack: NavigationStack { ProjectDashboardView() .id(UUID()) // Forces reinit } Still fails intermittently. ✅ Forced AsyncImage to Reload Tried appending a UUID() to the image URL: AsyncImage(url: URL(string: "\(imageUrl)?cacheBust=\(UUID().uuidString)")) Still fails when URL query parameters (?sv=...) are trimmed. I’d greatly appreciate any insights, code snippets, or debugging suggestions! Let me know if more logs or sample code would help. Thanks in advance!
0
0
133
2d
CloudKit Sharing Issue: "Unknown client: ChoreOrganizer"
I'm experiencing a persistent issue with CloudKit sharing in my iOS application. When attempting to present a UICloudSharingController, I receive the error message "Unknown client: ChoreOrganizer" in the console. App Configuration Details: App Name: ChoreOrganizer Bundle ID: com.ProgressByBits.ChoreOrganizer CloudKit Container ID: iCloud.com.ProgressByBits.ChoreOrganizer Core Data Model Name: ChoreOrganizer.xcdatamodeld Core Data Entity: Chore Error Details: The error "Unknown client: ChoreOrganizer" occurs when I present the UICloudSharingController This happens only on the first attempt to share; subsequent attempts during the same app session don't show the error but sharing still doesn't work All my code executes successfully without errors until UICloudSharingController is presented Implementation Details: I'm using NSPersistentCloudKitContainer for Core Data synchronization and UICloudSharingController for sharing. My implementation creates a custom CloudKit zone, saves both a record and a CKShare in that zone, and then presents the sharing controller. Here's the relevant code: @MainActor func presentSharing(from viewController: UIViewController) async throws { // Create CloudKit container let container = CKContainer(identifier: containerIdentifier) let database = container.privateCloudDatabase // Define custom zone ID let zoneID = CKRecordZone.ID(zoneName: "SharedChores", ownerName: CKCurrentUserDefaultName) do { // Check if zone exists, create if necessary do { _ = try await database.recordZone(for: zoneID) } catch { let newZone = CKRecordZone(zoneID: zoneID) _ = try await database.save(newZone) } // Create record in custom zone let recordID = CKRecord.ID(recordName: "SharedChoresRoot", zoneID: zoneID) let rootRecord = CKRecord(recordType: "ChoreRoot", recordID: recordID) rootRecord["name"] = "Shared Chores Root" as CKRecordValue // Create share let share = CKShare(rootRecord: rootRecord) share[CKShare.SystemFieldKey.title] = "Shared Tasks" as CKRecordValue // Save both record and share in same operation let recordsToSave: [CKRecord] = [rootRecord, share] _ = try await database.modifyRecords(saving: recordsToSave, deleting: []) // Present sharing controller let sharingController = UICloudSharingController(share: share, container: container) sharingController.delegate = shareDelegate // Configure popover if let popover = sharingController.popoverPresentationController { popover.sourceView = viewController.view popover.sourceRect = CGRect( x: viewController.view.bounds.midX, y: viewController.view.bounds.midY, width: 1, height: 1 ) popover.permittedArrowDirections = [] } viewController.present(sharingController, animated: true) } catch { throw error } } Steps I've already tried: Verified correct bundle ID and container ID match in all places (code, entitlements file, Developer Portal) Added NSUbiquitousContainers configuration to Info.plist Ensured proper entitlements in the app Created and configured proper provisioning profiles Tried both default zone and custom zone for sharing Various ways of saving the record and share (separate operations, same operation) Cleaned build folder, deleted derived data, reinstalled the app Tried on both simulator and physical device Confirmed CloudKit container exists in CloudKit Dashboard with correct schema Verified iCloud is properly signed in on test devices Console Output: 1. Starting sharing process 2. Created CKContainer with ID: iCloud.com.ProgressByBits.ChoreOrganizer 3. Using zone: SharedChores 4. Checking if zone exists 5. Zone exists 7. Created record with ID: <CKRecordID: 0x3033ebd80; recordName=SharedChoresRoot, zoneID=SharedChores:__defaultOwner__> 8. Created share with ID: <CKRecordID: 0x3033ea920; recordName=Share-C4701F43-7591-4436-BBF4-6FA8AF3DF532, zoneID=SharedChores:__defaultOwner__> 9. About to save record and share 10. Records saved successfully 11. Creating UICloudSharingController 12. About to present UICloudSharingController 13. UICloudSharingController presented Unknown client: ChoreOrganizer Additional Information: When accessing the CloudKit Dashboard, I can see that data is being properly synced to the cloud, indicating that the basic CloudKit integration is working. The issue appears to be specific to the sharing functionality. I would greatly appreciate any insights or solutions to resolve this persistent "Unknown client" error. Thank you for your assistance.
2
0
202
3d
Command Line Tool Embedding in SwiftUI App
I have added 2 command line tools in my swiftUI app for macOS, it was working fine locally, but it gives error when i try to make archive of it. I am not sure about the reason, but it was related to sandboxing the command line tools, after this i have tried multiple solutions but i am unable to resolve this issue, how should i handle the helper command line tools
2
0
172
2d
Searchable list with binding causes indexOutOfRange crash on iOS 18 physical device
Hi folks, Unsure if I've implemented some sort of anti-pattern here, but any help or feedback would be great. I've created a minimal reproducible sample below that lets you filter a list of people and mark individuals as a favourite. When invoking the search function on a physical device running iOS 18.3.1, it crashes with Swift/ContiguousArrayBuffer.swift:675: Fatal error: Index out of range. It runs fine on iOS 17 (physical device) and also on the various simulators I've tried (iOS 18.0, iOS 18.2, iOS 18.3.1). If I remove the toggle binding, the crash doesn't occur (but I also can't update the toggles in the view model). I'm expecting to be able to filter the list without a crash occurring and retain the ability to have the toggle switches update the view model. Sample code is below. Thanks for your time 🙏! import SwiftUI struct Person { let name: String var isFavorite = false } @MainActor class ViewModel: ObservableObject { private let originalPeople: [Person] = [ .init(name: "Holly"), .init(name: "Josh"), .init(name: "Rhonda"), .init(name: "Ted") ] @Published var filteredPeople: [Person] = [] @Published var searchText: String = "" { didSet { if searchText.isEmpty { filteredPeople = originalPeople } else { filteredPeople = originalPeople.filter { $0.name.lowercased().contains(searchText.lowercased()) } } } } init() { self.filteredPeople = originalPeople } } struct ContentView: View { @ObservedObject var viewModel = ViewModel() var body: some View { NavigationStack { List { ForEach($viewModel.filteredPeople, id: \.name) { person in VStack(alignment: .leading) { Text(person.wrappedValue.name) Toggle("Favorite", isOn: person.isFavorite) } } } .navigationTitle("Contacts") } .searchable(text: $viewModel.searchText) } } #Preview { ContentView() }```
4
0
144
4d
Simple console display test - preview not working as expected
Just learning Swift and SwiftUI, having fun in Xcode. I have the following custom view defined, but when I try to test it, the information doesn't get updated as I expect. When I use the button defined INSIDE the custom view, the update works as expected. When I use the button defined in the Preview body, it doesn't. The "lines" variable of the custom view appears not to be updated in that case. I know I'm missing something fundamental here about either view state binding or the preview environment, but I'm stumped. Any ideas? import SwiftUI struct ConsoleView: View { var maxLines : Int = 26 private enum someIDs { case textID} @State private var numLines : Int = 0 @State var lines = "a\nb\nc\n" var body: some View { VStack(alignment: .leading, spacing:0 ) { ScrollViewReader { proxy in ScrollView { Button("Scroll to Bottom") { withAnimation { proxy.scrollTo(someIDs.textID, anchor: .bottom) } } Text(lines) .id(someIDs.textID) .multilineTextAlignment(.leading) .frame(maxWidth: .infinity, alignment: .bottomLeading) .padding() .onChange ( of: lines) { withAnimation { proxy.scrollTo( someIDs.textID, anchor: .bottom) } } } Button("Add more") { writeln("More") //writeln(response) } } } } private func clipIfNeeded () { if (numLines>=maxLines) { if let i = lines.firstIndex(of: "\n") { lines = String(lines.suffix( from: lines.index(after:i))) } } } func writeln ( _ newText : String) { print("adding '\(newText)' to lines") //clipIfNeeded() write( newText ) write("\n") numLines += 1 print(lines) } func write ( _ newText : String) { lines += newText } } #Preview { VStack() { var myConsole = ConsoleView(lines: "x\ny\nz\n") myConsole Button("Add stuff") { myConsole.writeln("Stuff") } } }
2
0
204
4d
How to reduce CMSampleBuffer volume
Hello, Basically, I am reading and writing an asset. To simplify, I am just reading the asset and rewriting it into an output video without any modifications. However, I want to add a fade-out effect to the last three seconds of the output video. I don’t know how to do this. So far, before adding the CMSampleBuffer to the output video, I tried reducing its volume using an extension on CMSampleBuffer. In the extension, I passed 0.4 for testing, aiming to reduce the video's overall volume by 60%. My question is: How can I directly adjust the volume of a CMSampleBuffer? Here is the extension: extension CMSampleBuffer { func adjustVolume(by factor: Float) -> CMSampleBuffer? { guard let blockBuffer = CMSampleBufferGetDataBuffer(self) else { return nil } var length = 0 var dataPointer: UnsafeMutablePointer<Int8>? guard CMBlockBufferGetDataPointer(blockBuffer, atOffset: 0, lengthAtOffsetOut: nil, totalLengthOut: &length, dataPointerOut: &dataPointer) == kCMBlockBufferNoErr else { return nil } guard let dataPointer = dataPointer else { return nil } let sampleCount = length / MemoryLayout<Int16>.size dataPointer.withMemoryRebound(to: Int16.self, capacity: sampleCount) { pointer in for i in 0..<sampleCount { let sample = Float(pointer[i]) pointer[i] = Int16(sample * factor) } } return self } }
0
0
189
5d
.fileImporter not working on iPhone
I've been running into an issue using .fileImporter in SwiftUI already for a year. On iPhone simulator, Mac Catalyst and real iPad it works as expected, but when it comes to the test on a real iPhone, the picker just won't let you select files. It's not the permission issue, the sheet won't close at all and the callback isn't called. At the same time, if you use UIKits DocumentPickerViewController, everything starts working as expected, on Mac Catalyst/Simulator/iPad as well as on a real iPhone. Steps to reproduce: Create a new Xcode project using SwiftUI. Paste following code: import SwiftUI struct ContentView: View { @State var sShowing = false @State var uShowing = false @State var showAlert = false @State var alertText = "" var body: some View { VStack { VStack { Button("Test SWIFTUI") { sShowing = true } } .fileImporter(isPresented: $sShowing, allowedContentTypes: [.item]) {result in alertText = String(describing: result) showAlert = true } VStack { Button("Test UIKIT") { uShowing = true } } .sheet(isPresented: $uShowing) { DocumentPicker(contentTypes: [.item]) {url in alertText = String(describing: url) showAlert = true } } .padding(.top, 50) } .padding() .alert(isPresented: $showAlert) { Alert(title: Text("Result"), message: Text(alertText)) } } } DocumentPicker.swift: import SwiftUI import UniformTypeIdentifiers struct DocumentPicker: UIViewControllerRepresentable { let contentTypes: [UTType] let onPicked: (URL) -> Void func makeCoordinator() -> Coordinator { Coordinator(self) } func makeUIViewController(context: Context) -> UIDocumentPickerViewController { let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: contentTypes, asCopy: true) documentPicker.delegate = context.coordinator documentPicker.modalPresentationStyle = .formSheet return documentPicker } func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {} class Coordinator: NSObject, UIDocumentPickerDelegate { var parent: DocumentPicker init(_ parent: DocumentPicker) { self.parent = parent } func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { print("Success!", urls) guard let url = urls.first else { return } parent.onPicked(url) } func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { print("Picker was cancelled") } } } Run the project on Mac Catalyst to confirm it working. Try it out on a real iPhone. For some reason, I can't attach a video, so I can only show a screenshot
1
0
233
3d
Is Metal usable from Swift 6?
Hello ladies and gentlemen, I'm writing a simple renderer on the main actor using Metal and Swift 6. I am at the stage now where I want to create a render pipeline state using asynchronous API: @MainActor class Renderer { let opaqueMeshRPS: MTLRenderPipelineState init(/*...*/) async throws { let descriptor = MTLRenderPipelineDescriptor() // ... opaqueMeshRPS = try await device.makeRenderPipelineState(descriptor: descriptor) } } I get a compilation error if try to use the asynchronous version of the makeRenderPipelineState method: Non-sendable type 'any MTLRenderPipelineState' returned by implicitly asynchronous call to nonisolated function cannot cross actor boundary Which is understandable, since MTLRenderPipelineState is not Sendable. But it looks like no matter where or how I try to access this method, I just can't do it - you have this API, but you can't use it, you can only use the synchronous versions. Am I missing something or is Metal just not usable with Swift 6 right now?
0
0
294
1w
Why is UIViewController.dismissViewControllerAnimated marked as NS_SWIFT_DISABLE_ASYNC?
In the header for UIViewController, the method dismissViewControllerAnimated is declared like this: - (void)dismissViewControllerAnimated: (BOOL)flag completion: (void (^ __nullable)(void))completion NS_SWIFT_DISABLE_ASYNC API_AVAILABLE(ios(5.0)); NS_SWIFT_DISABLE_ASYNC means that there's no async version exposed like there would normally be of a method that exposes a completion handler. Why is this? And is it unwise / unsafe for me to make my own async version of it using a continuation? My use case is that I want a method that will sequentially dismiss all view controllers presented by a root view controller. So I could have this extension on UIViewController: extension UIViewController { func dismissAsync(animated: Bool) async { await withCheckedContinuation { continuation in self.dismiss(animated: animated) { continuation.resume() } } } func dismissPresentedViewControllers() async { while self.topPresentedViewController != self { await self.topPresentedViewController.dismissAsync(animated: true) } } var topPresentedViewController: UIViewController { var result = self while result.presentedViewController != nil { result = result.presentedViewController! } return result }
0
0
171
1w
Optimal Way of Getting Screen Resolution Using SwiftUI
Hi all, I am looking for a futureproof way of getting the Screen Resolution of my display device using SwiftUI in MacOS. I understand that it can't really be done to the fullest extent, meaning that the closest API we have is the GeometeryProxy and that would only result in the resolution of the parent view, which in the MacOS case would not give us the display's screen resolution. The only viable option I am left with is NSScreen.frame. However, my issue here is that it seems like Apple is moving towards SwiftUI aggressively, and in order to futureproof my application I need to not rely on AppKit methods as much. Hence, my question: Is there a way to get the Screen Resolution of a Display using SwiftUI that Apple itself recommends? If not, then can I rely safely on NSScreen's frame API?
2
0
160
1w
Moving SceneDelegate to a different target
I have a SwiftUI project which has the following hierarchy: IOSSceneDelegate (App target) - depends on EntryPoint and Presentation static libs. Presentation (Static library) - Depends on EntryPoint static lib. Contains UI related logic and updates the UI after querying the data layer. EntryPoint (Static library) - Contains the entry point, AppDelegate (for its lifecycle aspects) etc. I've only listed the relevant targets here. SceneDelegate was initially present in EntryPoint library, because the AppDelegate references it when a scene is created. public func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -&gt; UISceneConfiguration { // Set the SceneDelegate dynamically let sceneConfig: UISceneConfiguration = UISceneConfiguration(name: "mainWindow", sessionRole: connectingSceneSession.role) sceneConfig.delegateClass = SceneDelegate.self return sceneConfig } The intent is to move the SceneDelegate to the Presentation library. When moved, the EntryPoint library fails to compile because it's referencing the SceneDelegate (as shown above). To remove this reference, I tried to set up the SceneDelegate in the old way - In the info.plist file, mention a SceneConfiguration and set the SceneDelegate in Presentation. // In the Info.plist file &lt;key&gt;UIApplicationSceneManifest&lt;/key&gt; &lt;dict&gt; &lt;key&gt;UIApplicationSupportsMultipleScenes&lt;/key&gt; &lt;true/&gt; &lt;key&gt;UISceneConfigurations&lt;/key&gt; &lt;dict&gt; &lt;key&gt;UIWindowSceneSessionRoleApplication&lt;/key&gt; &lt;array&gt; &lt;dict&gt; &lt;key&gt;UISceneConfigurationName&lt;/key&gt; &lt;string&gt;Default Configuration&lt;/string&gt; &lt;key&gt;UISceneDelegateClassName&lt;/key&gt; &lt;string&gt;Presentation.SceneDelegate&lt;/string&gt; &lt;/dict&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/dict&gt; // In the AppDelegate public func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -&gt; UISceneConfiguration { // Refer to a static UISceneconfiguration listed in the info.plist file return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } As shown above, the Presentation.SceneDelegate is referred in the Info.plist file and the reference is removed from the AppDelegate (in EntryPoint library). The app target compiles, but when I run it, the SceneDelegate is not invoked. None of the methods from the SceneDelegate (scene(_:willConnectTo:options:), sceneDidDisconnect(_:), sceneDidEnterBackground(_:) etc.) are invoked. I only get the AppDelegate logs. It seems like the Configuration is ignored because it was incorrect. Any thoughts? Is it possible to move the SceneDelegate in this situation?
0
1
194
1w
Swipe gestures for widgets
Hey, I am building some widgets and I'm quite surprised that Swipe gestures for widgets is not supported. It means the user must sacrifice home screen real estate to view multiple widgets to receive the same information. Ideally, swiping left / right inside of the widget should give a developer access to present different views. I realize that it means that a user would need to swipe outside of the widget, (or swipe to the beginning/end of the series of views inside of the widget) for the page to swipe, but I'd argue that this is the intuitive behavior of what widget scrollview would or should look like anyway.
1
0
225
1w
swift编写的工程无法获取OC制作的sdk传输的数据
在使用xcode15.2与iOS14.2版本的手机进行调试时,发现OC编译的sdk无法正常传输数据给swift编写的项目。当我的手机连接xcode调试的时候,数据能够正常传输、转换。当我断开手机与xcode的连接的时候,就无法正常获取数据了。而这个问题目前我只发现在iOS14.2中。当我使用iOS17与iOS18手机调试时没有出现这个问题。请问有没有人遇到过相似的问题。
1
0
236
1w