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

Posts under Swift tag

200 Posts

Post

Replies

Boosts

Views

Activity

Immediate crash of Apple Watch simulator when typing a key
I get a crash in Apple Watch simulator (Series 9 45mm 18.0) as soon as the app launch if I type anything on external keyboard (just hitting command key for instance to capture a screenshot). Same crash on series 7 (45mm, OS 18.1) But app works normally when I use mouse to interact with the app on simulator. App does not crash on real device (Watch 4 OS 10.4.1). Nor does it crash on Series 6 simulator (44 mm OS 17.4). Here are the log I could collect (apparently, they contain sensitive language !!! so I attach as a file.: Attached logs
2
0
399
Mar ’25
Change app language on Apple Watch simulator
I feel a bit dumb now. I once succeeded to change the language of an app on Watch simulator. So it is possible. And I'm not able to repeat (fool of me I did not took note of how I did it). I just remember it was simply through some language settings selection, may be rebooting the Mac, but not by changing anything in code. Does someone know how to do ?
3
0
468
Mar ’25
AppKit document project reports an error when opening a new document in Swift 6
In an AppKit document-based project created by Xcode, setting canConcurrentlyReadDocuments to true allows new documents to open normally in Swift 5, but switching to Swift 6 causes an error. Judging from the error message, it seems to be a threading issue, but I’m not sure how to adjust the code to support the Swift 6 environment. The project is the most basic code from an Xcode-created document-based project without any modifications, except for changing the Swift version to 6 and setting canConcurrentlyReadDocuments to true. Source code: https://drive.google.com/file/d/1ryb2TaU6IX884q0h5joJqqZwSX95Q335/view?usp=sharing AppDelegate.swift import Cocoa @main class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { return true } } Document.swift import Cocoa class Document: NSDocument { override init() { super.init() // Add your subclass-specific initialization here. } override class var autosavesInPlace: Bool { return true } override class func canConcurrentlyReadDocuments(ofType typeName: String) -> Bool { true } override func canAsynchronouslyWrite(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType) -> Bool { true } override func makeWindowControllers() { // Returns the Storyboard that contains your Document window. let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil) let windowController = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("Document Window Controller")) as! NSWindowController self.addWindowController(windowController) } override func data(ofType typeName: String) throws -> Data { // Insert code here to write your document to data of the specified type, throwing an error in case of failure. // Alternatively, you could remove this method and override fileWrapper(ofType:), write(to:ofType:), or write(to:ofType:for:originalContentsURL:) instead. // throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) return Data() } override func read(from data: Data, ofType typeName: String) throws { // Insert code here to read your document from the given data of the specified type, throwing an error in case of failure. // Alternatively, you could remove this method and override read(from:ofType:) instead. // If you do, you should also override isEntireFileLoaded to return false if the contents are lazily loaded. // throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) } } ViewController.swift import Cocoa class ViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } }
1
1
540
Mar ’25
Interacting with the Notes application
Hello, Relatively new to AppleScripts in current gen (I've used it back in 2010s) and would like some help if someone can point me in the right direction. Is AppleScript the best/only way to interact with Notes application? (I'm on Sequioa) 1.1 I've tried to use LLM to generate a Swift app, but it still calls out to AppleScripts, so I'm wondering if I'm missing something. 1.2 If I'm going down a rabbit hole, I'd like to stop since I want to finish this quick task and move on and or fall deeply in love with AppleScripts... whichever comes first. Is There a better way to write notes? Script Editor is still a minimal IDE, I'd love to find something that will do some auto completion/suggestions because the documentation in the Script Editor is still a tad weak. (I'm used to interpreted languages like bash, ruby, etc...) where if I don't understand something I just dig into the code instead of turse documentation that just exposes public end points and does not tell you much more :( My problem: I'd like to set up a cron that periodically checks my notes, and cleans up the shared notes. Basically it's a shared set of notes that have checklist on it and cleans up. (weekly chores etc...) I want to read the notes, find out which ones have been marked checked. Reset the ones that are done, leave unfinished ones alone and reset the old ones. This is how far I've gotten: let appleScript = """``` tell application "Notes" set targetNote to note "\Test" of default account return body of targetNote end tell That works like a charm, Kind of dumb because I rather use and ID of the note not the name :( It returns the following <div><b><span style=\\"font-size: 24px\\">Test</span></b></div> <div><br></div> <ul> <li> Not Done</li> <li>Done</li> <li>Not Done yet</li> </ul> <div><br></div> <div>Single line</div> Which is a good start! Issues: There is no way to tell which Item is marked "Checked" and which one is not :( Any helps is greatly appreciated!
1
0
279
Mar ’25
Unable to Sign in to Apple ID in Xcode – Credentials Not Recognized
Hi everyone, I am experiencing an issue where I am unable to sign in to my Apple ID within Xcode. Even after updating my password and ensuring that all my credentials are correct, I continue to receive an "Incorrect username or password" error. However, I can successfully log in to Apple Developer Portal, iCloud, and Apple ID settings using the same credentials. Steps I've Taken to Resolve the Issue: Updated Software I have updated macOS Sequoia and Xcode to the latest versions. I have also verified that my Apple Developer certificates are up to date. Tried Resetting Authentication in macOS I removed all related entries for Xcode, Apple ID, and Developer from Keychain Access. Logged out of my Apple ID from System Settings and restarted my Mac. Logged back in and retried signing in to Xcode. Checked Authentication & Security Settings I verified that two-factor authentication (2FA) is enabled. Tried appending the verification code directly to the password when logging into Xcode. Checked Xcode Developer Directory Ran sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer Verified using xcode-select -p, which correctly pointed to the Xcode Developer directory. Tried Resetting Developer Tools Removed and reinstalled Command Line Tools (xcode-select --install). Accepted the Xcode license agreement (sudo xcodebuild -license). Reinstalled Xcode Completely uninstalled Xcode using sudo rm -rf /Applications/Xcode.app and reinstalled it from the Mac App Store. Problem Summary: Xcode does not recognize my Apple ID credentials, despite them being correct. I can successfully log in to Apple’s web services, but not to Xcode. I have already attempted multiple fixes, including resetting keychain entries, reinstalling Xcode, and verifying system configurations. I would appreciate your guidance on resolving this issue, as I need access to my Apple Developer account within Xcode to continue working on my app. Thank you for your support.
1
0
374
Mar ’25
CryptoTokenKit Network Cryptographic Tokens
Hello, It is mentioned in CryptoTokenKit documentation: You use the CryptoTokenKit framework to easily access cryptographic tokens. Tokens are physical devices built in to the system, located on attached hardware (like a smart card), or accessible through a network connection. However, it looks like there is lack of documentation with simple example, how to access network token. I have a certificates in HSM (hardware secure module), which is accessible on network, and I'd like to access certificates on HSM on my Mac. Does anybody know, where to start with implementation? Thank you.
3
0
1.4k
Mar ’25
Why is this causing my app to crash?
I'm developing an app for my watch and have a list of different classes (referred to as 'courses' to avoid confusion) that I take in school, eg: struct Course { let name: String let icon: String let room: String let colour: String let listName: String let listIcon: String init(name: String, icon: String, room: String? = nil, colour: String, listName: String? = nil, listIcon: String? = nil) { self.name = name self.icon = icon self.room = room ?? "None" self.colour = colour self.listName = listName ?? name self.listIcon = listIcon ?? icon+".circle.fill" } } // here's a few of my Course variables (there are lots more I've excluded) let MathsCourse = Course(name: "Maths", icon: "number", room: "FT5", colour: "Rose") let English6 = Course(name: "English", icon: "book.closed", room: "BT6", colour: "Lemon") let LunchPeriod = Course(name: "Lunch", icon: "fork.knife", room: "food", colour: "White") and I have designed a 'list view' of all the courses I have on whatever day it is. I used to define a different View for every course I defined but I merged the list data with the overall Course and replaced the Views with something that I should be able to call repeatedly and pass in a course to use, but unfortunately it's not working. (yes, I'm making a timetable app) This is the template for a 'list view' for a class: struct courseListView: View { var localcourse: Course var localtime: String var body: some View { HStack{ Image(systemName: localcourse.listIcon) .foregroundColor(Color(localcourse.colour)) .padding(.leading, 5) Text(localcourse.name) .bold() Spacer() Text(localtime) Text(roomOrBlank(course: localcourse)).bold().padding(.trailing, 5) } .padding(.bottom, 1) .background(currentCourse.name==localcourse.name ? Color(localcourse.colour).colorInvert(): nil) } } Then I should be able to programmatically work out what courses I have that day (I haven't scripted that bit yet), and compose a view containing all the courses: struct ListView: View { var body: some View { ScrollView { VStack(alignment: .leading) { courseListView(localcourse: MathsCourse, localtime: "10:00") // ^^^ note above line; I'll come back to this // the idea is I can repeat that for a bunch of courses: courseListView(localcourse: English6, localtime: "11:00") courseListView(localcourse: LunchPeriod, localtime: "12:00") } } } } Then be able to call all that in my @main: @main struct Timetaber_Watch_AppApp: App { var body: some Scene { WindowGroup { TabView{ HomeView() ListView() SettingsView() } .tabViewStyle(.carousel) .onAppear() { log() } } } } Unfortunately, each time I try to get a list view for a course, // if you need a reminder: courseListView(localcourse: MathsCourse, localtime: "10:00") ...even only calling it once causes my entire app to crash. Here's an excerpt from the crash report: Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x0000000180210194 Termination Reason: SIGNAL 5 Trace/BPT trap: 5 Terminating Process: exc handler [14932] Triggered by Thread: 0 Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 libdispatch.dylib 0x180210194 _dispatch_once_wait.cold.1 + 28 1 libdispatch.dylib 0x1801db4f4 _dispatch_once_wait + 184 2 ??? 0x3400200d0 ??? 3 ??? 0x340020198 ??? 4 ... So... Anyone know what's happening?
3
0
275
Mar ’25
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
447
Feb ’25
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
314
Feb ’25
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
387
Feb ’25
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
404
Feb ’25
.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
398
Feb ’25
ITMS-90429: Invalid Swift Support
Build the archive, validating and uploading it to App Store Connect - TestFlight is successful from Xcode (16.0, macOS 15.1.1). Although after that the build is rejected stating : ITMS-90429: Invalid Swift Support - The files libswiftCoreFoundation.dylib, libswiftCoreData.dylib, libswiftCore.dylib, libswiftFoundation.dylib, libswift_Concurrency.dylib, libswiftObjectiveC.dylib aren’t at the expected location /Payload/Runner.app/Frameworks. Move the file to the expected location, rebuild your app using the current public (GM) version of Xcode, and resubmit it. Cross checked the Archive and .ipa file, where we found that the mentioned .dylib files are actually present inside the "/Payload/Runner.app/Frameworks" folder, and all the ".dylib" files are also present in the "SwiftSupport/iphoneos" folder. Scenario : using tdLib compilation "libtdjson.xcframework" (embedded & signed) for ios arm64 placed under "Framworks", in my Flutter application, calling methods via "Method Channels", interacting with AppDelegate.swift file where the tdLib methods are being called from the compiled library. All "swift support settings" are enabled in Xcode while archiving and building the application.
3
0
987
Feb ’25
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
358
Feb ’25