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

Posts under Swift tag

200 Posts

Post

Replies

Boosts

Views

Activity

Programming Languages Resources
This topic area is about the programming languages themselves, not about any specific API or tool. If you have an API question, go to the top level and look for a subtopic for that API. If you have a question about Apple developer tools, start in the Developer Tools & Services topic. For Swift questions: If your question is about the SwiftUI framework, start in UI Frameworks > SwiftUI. If your question is specific to the Swift Playground app, ask over in Developer Tools & Services > Swift Playground If you’re interested in the Swift open source effort — that includes the evolution of the language, the open source tools and libraries, and Swift on non-Apple platforms — check out Swift Forums If your question is about the Swift language, that’s on topic for Programming Languages > Swift, but you might have more luck asking it in Swift Forums > Using Swift. General: Forums topic: Programming Languages Swift: Forums subtopic: Programming Languages > Swift Forums tags: Swift Developer > Swift website Swift Programming Language website The Swift Programming Language documentation Swift Forums website, and specifically Swift Forums > Using Swift Swift Package Index website Concurrency Resources, which covers Swift concurrency How to think properly about binding memory Swift Forums thread Other: Forums subtopic: Programming Languages > Generic Forums tags: Objective-C Programming with Objective-C archived documentation Objective-C Runtime documentation Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
0
0
1.5k
Oct ’25
Putting 2 existing pdf pages side by side (half size) in a new pdf
In Swift, iOS, I have a pdf file. I want to take the pages 2 by 2 and put them side by side, on the new page. For this, I have to scale initial pages half size and rotate .pi/2. I managed to achieve this by converting pdf pages to UIImages and using a UIGraphicsImageRenderer. But with a critical loss of resolution. I've tried improving the resolution by creating images as jpegData(withCompressionQuality: 1.0), to no avail. So I would need to work directly on the pdf pages using CGPDFDocument format. The code structure is as follows, to insert a single scaled page: for iPage in … { if let _page = theCGPdfDocument.page(at: 1) { var _pageRect: CGRect = _page.getBoxRect(CGPDFBox.mediaBox) writeContextInDestination!.beginPage(mediaBox: &_pageRect) // translate to compensate for the flip caused displacement writeContextInDestination!.translateBy(x: _pageRect.size.width, y: _pageRect.size.height) Scale (-1, -1) // rotate 180° // add rotate as needed writeContextInDestination!.scaleBy(x: -1, y: -1) writeContextInDestination!.clip(to: _pageRect) writeContextInDestination!.drawPDFPage(_page) writeContextInDestination!.endPage() // end the current page } } writeContextInDestination!.closePDF() But I do not succeed in inserting the drawing of the second page. I've tried repeating lines 7 to 11 for a second page at line 13. No success. What is the direction to look for ?
1
0
54
9h
NavigationTitle in LiquidGlass style
Hello everyone. I want to do navigationTitle (located on the top side on MacOS system) in LiquidGlass style. now my solution look like: just black rectangle. But i want like this: opacity and LiquidGlass. Like in Photo app in MacOS. Please help me, thank you in advance. My code: struct RootView: View { @Environment(\.horizontalSizeClass) var hSize var body: some View { if hSize == .regular { DesktopLayout() .navigationTitle("title") .toolbarBackground(.ultraThinMaterial, for: .automatic) } else { MobileLayout() } } }
1
0
472
15h
Two errors in debug: com.apple.modelcatalog.catalog sync and nw_protocol_instance_set_output_handler
We get two error message in Xcode debug. apple.model.catalog we get 1 time at startup, and the nw_protocol_instance_set_output_handler Not calling remove_input_handler on 0x152ac3c00:udp we get on sartup and some time during running of the app. I have tested cutoff repos WS eg. But nothing helpss, thats for the nw_protocol. We have a fondationmodel in a repo but we check if it is available if not we do not touch it. Please help me? nw_protocol_instance_set_output_handler Not calling remove_input_handler on 0x152ac3c00:udp com.apple.modelcatalog.catalog sync: connection error during call: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.modelcatalog.catalog was invalidated: Connection init failed at lookup with error 159 - Sandbox restriction." UserInfo={NSDebugDescription=The connection to service named com.apple.modelcatalog.catalog was invalidated: Connection init failed at lookup with error 159 - Sandbox restriction.} reached max num connection attempts: 1 The function we have in the repo is this: public actor FoundationRepo: JobDescriptionChecker, SubskillSuggester { private var session: LanguageModelSession? private let isEnabled: Bool private let shouldUseLocalFoundation: Bool private let baseURLString = "https://xx.xx.xxx/xx" private let http: HTTPPac public init(http: HTTPPac, isEnabled: Bool = true) { self.http = http self.isEnabled = isEnabled self.session = nil guard isEnabled else { self.shouldUseLocalFoundation = false return } let model = SystemLanguageModel.default guard model.supportsLocale() else { self.shouldUseLocalFoundation = false return } switch model.availability { case .available: self.shouldUseLocalFoundation = true case .unavailable(.deviceNotEligible), .unavailable(.appleIntelligenceNotEnabled), .unavailable(.modelNotReady): self.shouldUseLocalFoundation = false @unknown default: self.shouldUseLocalFoundation = false } } So here we decide if we are going to use iPhone ML or my backend-remote?
1
0
99
19h
SpeechAnalyzer.start(inputSequence:) fails with _GenericObjCError nilError, while the same WAV succeeds with start(inputAudioFile:)
I'm trying to use the new Speech framework for streaming transcription on macOS 26.3, and I can reproduce a failure with SpeechAnalyzer.start(inputSequence:). What is working: SpeechAnalyzer + SpeechTranscriber offline path using start(inputAudioFile:finishAfterFile:) same Spanish WAV file transcribes successfully and returns a coherent final result What is not working: SpeechAnalyzer + SpeechTranscriber stream path using start(inputSequence:) same WAV, replayed as AnalyzerInput(buffer:bufferStartTime:) fails once replay starts with: _GenericObjCError domain=Foundation._GenericObjCError code=0 detail=nilError I also tried: DictationTranscriber instead of SpeechTranscriber no realtime pacing during replay Both still fail in stream mode with the same error. So this does not currently look like a ScreenCaptureKit issue or a Python integration issue. I reduced it to a pure Swift CLI repro. Environment: macOS 26.3 (25D122) Xcode 26.3 Swift 6.2.4 Apple Silicon Mac Has anyone here gotten SpeechAnalyzer.start(inputSequence:) working reliably on macOS 26.x? If so, I'd be interested in any workaround or any detail that differs from the obvious setup: prepareToAnalyze(in:) bestAvailableAudioFormat(...) AnalyzerInput(buffer:bufferStartTime:) replaying a known-good WAV in chunks I already filed Feedback Assistant: FB22149971
0
0
123
1d
How to stop ios 26 glass effect UI in ios app
Hi everyone, I want to avoid the iOS 26 Liquid Glass effect in my app’s UI. While researching, I found the following possible solution: Steps: Go to Info.plist Add the key: UIDesignRequiresCompatibility Type: Boolean Value: YES I have a few questions about this approach: According to the Apple Developer website, this seems to be a temporary solution. How long will this continue to work, and what would be the recommended long-term solution? Which iOS versions does this support (both older and upcoming versions)? If this method is not recommended, is there another way to disable or avoid the glass effect across the entire app without making major UI changes? Any guidance or suggestions would be greatly appreciated. Thank you!
1
0
94
2d
Restrict app tp be installed on iPhone only
Hey everyone, I'm developing an iOS only app and want to make sure it can not be installed on iPads. Using Xcode 26, Targets/Appname/General/Supported Destination - I have iPhone only as destination and in the Info.plist I have this: UIDeviceFamily 1 UIRequiredDeviceCapabilities telephony Is there anything else need to do to make sure it can't be installed on iPads? Thanks in advance
1
0
23
2d
Data Persistence not functioning upon refresh
Hello, I am attempting to implement a simple button that loads persistent data from a class (see below). Button("Reload Data") { while tableData2.isEmpty == false{ tableData2.remove(at: 0) } while tableView.isEmpty == false{ tableView.remove(at: 0) } //update if csvData.isEmpty == false{ for superRow in csvData[0].tableData2{ tableData2.append(superRow) } for supperRow in csvData[0].tableView{ tableView.append(supperRow) } print("Item at 0: \(csvData[0].tableData2[[0][0]])") print("\(tableData2[0][0])") } else { print("csvData is empty") } } This button DOES work to appropriately print the data stored at the printed location once loaded in initially. The problem is that it doesn’t work across app restarts, which is the whole point of the button. Below I will include the rest of the relevant code with notes: In contentView declaring the persistant variables: Query private var csvData: [csvDataPersist] Environment(\.modelContext) private var modelContext The simple class of data I’m storing/pulling to/from: @Model class csvDataPersist{ var tableView: [[String]] = [] var tableData2: [[String]] = [] init(tableView: [[String]], tableData2: [[String]]) { self.tableView = tableView self.tableData2 = tableData2 } } In (appname)App: I tried both locations of the model container but it didn’t seem to matter var body: some Scene { WindowGroup { ContentView() .modelContainer(for: csvDataPersist.self) } //.modelContainer(for: csvDataPersist.self) .modelContainer(sharedModelContainer) } How I’m attempting to save the data: let newCSVDataPersist = csvDataPersist(tableView: tableView, tableData2: tableData2) //modelContext.rollback() //for superrow in csvData.count{ // csvData[superrow].tableData2.removeAll() //} //modelContext.rollback() //csvData[0].tableData2.removeAll() //csvData[0].tableView.removeAll() if csvData.isEmpty == false { print("not empty, deleting prev data") modelContext.delete(csvData[0]) } else { print("it empty, load data.") } modelContext.insert(newCSVDataPersist) //try modelContext.save() Note that I’ve tried just about every combination of enabling and disabling the commented out lines. This is the part of the code I am the least confident in, but after trying for hours to troubleshoot on my own I would appreciate any input from the community. Something else that may be of note, in a previous attempt, upon a second startup, the terminal would print: "coredata: error: error: persistent history (random number) has to be truncated due to the following entities being removed: ( csvdatapersist )" Why is csvDataPersist getting removed? What is it getting removed by? Looking up this error was fruitless. Most sites instructed me to basically hard reset my simulators, clean the build, restart my computer, and try again. I've done all of these things about a hundred times at this point, with no results. Any help would be much appreciated!
3
0
84
4d
CloudKit Sync Stalls During Initial Large Data Hydration on New Device (SwiftData Local-First Architecture)
Hi everyone, I’m facing an issue with CloudKit sync getting stuck during initial device migration in my SwiftData-based app. The app follows a local-first architecture using SwiftData + CloudKit sync, and works correctly for: ✔ Incremental sync ✔ Bi-directional updates ✔ Small datasets However, when onboarding a new device with large historical data, sync becomes extremely slow or appears stuck. Even after two hours data is not fully synced. ~6900 Transactions 🚨 Problem When installing the app on a new iPhone and enabling iCloud sync: • Initial hydration starts • A small amount of data syncs • Then sync stalls indefinitely Observed behaviour: • iPhone → Mac sync works (new changes sync back) • Mac → iPhone large historical migration gets stuck • Reinstalling app / clearing container does not resolve issue • Sync never completes full migration This gives the impression that: CloudKit is trickling data but not progressing after a certain threshold. The architecture is: • SwiftData local store • Manual CloudKit sync layer • Local-first persistence • Background push/pull sync So I understand: ✔ Conflict resolution is custom ✔ Initial import may not be optimized by default But I expected CloudKit to eventually deliver all records. Instead, the new device remains permanently in a “partial state”. ⸻ 🔍 Observations • No fatal CloudKit errors • No rate-limit errors • No quota issues • iCloud is available • Sync state remains “Ready” • Hydration remains “mostlyReady” Meaning: CloudKit does not report failure — but data transfer halts. ⸻ 🤔 Questions Would appreciate guidance on: Is CloudKit designed to support large initial dataset migration via manual sync layers? Or is this a known limitation vs NSPersistentCloudKitContainer? ⸻ Does CloudKit internally throttle historical record fetches? Could it silently stall without error when record volume is high? ⸻ Is there any recommended strategy for: • Bulk initial migration • Progressive hydration • Forcing forward sync progress ⸻ Should initial migration be handled outside CloudKit (e.g. via file transfer / backup restore) before enabling sync? ⸻ 🎯 Goal I want to support: • Large historical onboarding • Multi-device sync • User-visible progress Without forcing migration to Core Data. ⸻ 🙏 Any advice on: • Best practices • Debugging approach • CloudKit behavior in such scenarios would be greatly appreciated. Thank you!
1
0
93
5d
How can I change the output dimensions of a CoreML model in Xcode when the outputs come from a NonMaximumSuppression layer?
After exerting a custom model with nms=True. In Xcode, the outputs show as: confidence: MultiArray (0 × 5) coordinates: MultiArray (0 × 4) I want to set fixed shapes (e.g., 100 × 5, 100 × 4), but Xcode does not allow editing—the shape fields are locked. The model graph shows both outputs come directly from a NonMaximumSuppression layer. Is it possible to set fixed output dimensions for NMS outputs in CoreML?
2
0
128
5d
Provisional Permission is not working as expected in iOS 16
We recently developed the provisional permission for our app, but we have noticed that is not working as expected in iOS 16 (We have tested only there). Currently we request the permissions like this: UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound, .provisional]) { [weak self] _, _ in // here we register for pushes in case authorizationStatus is provisional or authorised } What happens is we do get the 1st notification with the keep CTA - once tapped we see that there pops an action: "Deliver Immediately", but even though the user selects that, we still see under setting the pushes are marked as "Deliver Quietly". In addition to this the sound and bage still stay as toggled off - and the lock screen and banner as well stay off. Basically, nothing changes after the user selects "Deliver Immediately"
1
5
792
5d
Backgrounded app - Local Notifications
I'm working on an app that syncs with Apple Health events. Every time an event occurs, the app should send a notification. The problem occurs when the app is backgrounded or force-closed; it can no longer send local notifications, and because these events can occur at any time, scheduled notifications can't be used. I'm just wondering if anyone's found a creative way around this. I know we can't override system behaviour, I'm just thinking of other alternative solutions for the matter.
1
0
96
6d
[After iPhone migration] Health app permissions for connected app are not shown
After upgrading to a new iPhone and restoring from an iCloud backup using the same Apple ID, I noticed an issue with Health app permissions. ■ What is happening On my previous iPhone, an app had permission to read step count data. After restoring to the new iPhone, the app still appears in the Health app under Sources. However, when I tap the app, the usual data type permission toggles (such as Steps) are not displayed at all. As a result, the app is unable to read step count data. ■ Additional details The app itself seems to be recognized as a Health data source. However, the data type permission screen is empty. No ON/OFF switches are shown. The backup was created on iOS 18, and the restore was performed on iOS 26. I have not yet confirmed whether this also happens with other iOS version combinations. ■ Questions Is it expected behavior that Health app permissions (per data type) are not restored via iCloud backup? Has anyone experienced a similar situation where the app appears under Sources but the permission options are missing? If so, how did you resolve it? Any information from users who have experienced the same issue would be greatly appreciated.
4
0
150
1w
init?(coder: NSCoder) or init?(coder: (NSCoder?))
In this code, I use in some places required init?(coder: (NSCoder?)) { // Init some properties super.init(coder: coder!) } And in other places required init?(coder: NSCoder) { super.init(coder: coder) // Init some properties } Both seem to work. Is there a preferred one ? In which cases ? Or should I always use the second one ? And can super be called at anytime ?
2
0
448
1w
Can NWConnection.receive(minimumIncompleteLength:maximumLength:) return nil data for UDP while connection remains .ready?
I’m using Network Framework with UDP and calling: connection.receive(minimumIncompleteLength: 1, maximumLength: 1500) { data, context, isComplete, error in ... // Some Logic } Is it possible for this completion handler to be called with data==nil if I haven't received any kind of error, i.e., error==nil and the connection is still in the .ready state?
5
0
137
1w
Referencing IBOutlet to its class or to file's owner
In this Mac App, I have an IBOutlet (which is defined as instance of a subclass of NSView). When I connect the IBOutlet to the code, referencing as file's owner, it works OK. But if I reference to the class, it crashes, when I access a specific IBOutlet (but other IBOutlets are accessed just before it without crashing).. The IBOutlet turnPageControl is defined as instance of subclass of NSView. Note: I have implemented several init methods: override init(window: NSWindow!) { } required init?(coder: (NSCoder?)) { } // Yes, (NSCoder?) convenience init(parameters) { // loading from nib } override func windowDidLoad() { super.windowDidLoad() // Access turnpageControl I get those calls before crash: init(window:) init(parameters:) init(window:) windowDidLoad() -> crash inside on accessing the IBOutlet for turnPageControl.isHidden = true Is there any reason to this ?
1
0
83
1w
SwiftUI Link view corrupts destination URLs when using a leading-zero padded IPv4 address.
There appears to be a bug in Link with IPv4 addresses with padding in the second octet, on macOS and iOS both. struct LinkViewBug: View { let works = URL(string: "http://172.16.1.1")! let alsoWorks = URL(string: "http://172.16.001.001")! let doesntWork = URL(string: "http://172.016.001.001")! let alsoDoesntWork = URL(string: "http://172.016.1.1")! var body: some View { // destination -> http://172.16.1.1 Link(works.formatted(), destination: works) Link(alsoWorks.formatted(), destination: alsoWorks) // destination -> http://172.14.1.1 ? Link(doesntWork.formatted(), destination: doesntWork) Link(alsoDoesntWork.formatted(), destination: alsoDoesntWork) } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
0
0
49
1w
Rendering Multi-Page PDF with SwiftUI View
I have the following code that renders a one-page PDF: func render() -> URL { let renderer = ImageRenderer(content: pdfView()) let url = URL.documentsDirectory.appending(path: "filename.pdf") renderer.render { size, context in var document = CGRect(x: 0, y: 0, width: 2550, height: 3300) guard let pdf = CGContext(url as CFURL, mediaBox: &document, nil) else { return } pdf.beginPDFPage(nil) context(pdf) pdf.endPDFPage() pdf.closePDF() } return url } func pdfView() -> some View { Text("View") } How can this be modified so that it renders a PDF with more than one page?
2
0
611
1w
Quick Look Extension does not load MapKit map properly anymore, after macOS Sequoia
It appears that starting with macOS Sequoia, Quick Look Preview extension no longer loads MapKit maps correctly anymore. Map tiles do not appear, leaving users with a beige background. Users report that polylines do render correctly, but annotations appears black. This was previously working fine in prior macOS versions including Sonoma. STEPS TO REPRODUCE Create a macOS app project, with an associated document. Ensure project has a Quick Look preview extension, with necessary basic setups. Ensure that the extension mentioned in (2) must have a MKMapView. Any other cosmetic changes, etc, does not need to be implemented to observe the base issue. Do note that it has been reported that in addition to the map tiles not loading, annotations don't render correctly as well.
5
2
1k
2w
Announcing the Swift Student Challenge 2026
Announcing the Swift Student Challenge 2026 Every year, Apple’s Swift Student Challenge celebrates the creativity and ingenuity of student developers from around the world, inviting them to use Swift and Xcode to solve real-world problems in their own communities and beyond. Learn more → https://developer.apple.com/swift-student-challenge/ Submissions for the 2026 challenge will open February 6 for three weeks, and students can prepare with new Develop in Swift tutorials and Meet with Apple code-along sessions. The Apple Developer team is here is to help you along the way - from idea to app, post your questions at any stage of your development here in this forum board or be sure to add the Swift Student Challenge tag to your technology-specific forum question. Your designs. Your apps. Your moment.
15
3
2.1k
2w