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

Swift optimization issue in macOS Sequoia
I'm using this library for encoding / decoding RSA keys. https://github.com/Kitura/BlueRSA It's worked fine up until macOS sequoia. The issue I'm having is the tests pass when in Debug mode, but the moment I switch to Release mode, the library no longer works. I ruled this down the swift optimization level. If I change the Release mode to no optimization, the library works again. Wondering where in the code this could be an issue? How would optimization break the functionality?
0
0
17
1h
[cxx-interop] Avoid breaking changes after enabling Swift C++ interoperability in library
Hi all, Background: I am working as a library developer and would like to enable Swift C++ interoperability in our library. Our library supports both CocoaPods and SPM. Question: I would like to know whether it is possible to avoid breaking changes bring to the library users after enabling Swift C++ interoperability. In my experiment, all apps and packages depend on the library needs to enable interoperability in Xcode or package manage tools, otherwise the source code cannot be complied. I am wondering is there any ways to bypass this? For example, is there a way to only enable Swift C++ interoperability only in our libraries?
0
0
26
2h
JavascriptCore and event loop / timers
JavascriptCore doesn't come with any support for setTimeout (which is an API on the window/DOM object not provide din JavaScriptCore). So you need to implement a version of this yourself - no worries on that (there are examples to refer to out there, so it is fairly easy to set this up). But I have come across an issue with this that I am not sure how to handle properly. It relates to when the timer callback fires and runs code in the JavaScript engine itself. Consider this code snippet (assume I have provided an implementation of setTimeout): console.log('Hello - here we go'); setTimeout(() => { console.log('Hi from setTimeout callback ...'); }, 0); Promise.resolve().then(() => { console.log('Hi from promise'); }); console.log('Hi from main block'); In Node.js or say Safari, I would see this output: Hello - here we go Hi from main block Hi from promise Hi from setTimeout callback ... So the promise then() is handled before the settimeout callback is handled. I think this is basically because Promise then() handlers are pushed onto something like a microtask queue, and the setttimeout callbacks on a separate queue, and the microtask queue is emptied before any other queue is processed (after completing the current event loop of course). But when I implement this in JavaScript core, I don't always see the above - instead I can have: Hello - here we go Hi from main block Hi from setTimeout callback ... Hi from promise So the timeout callback can be run BEFORE the promise handler. This obviously is different from Node or Safari. Now I assume that is because the timeout callback is triggered from Swift native code that uses the call() API on a JSValue object that is provided when the settimeout is given to the native layer to process. And it seems that when native code attempts to execute JavaScript code (via call() or similar) then this is just executed as soon as possible - obviously not interrupting the Javascript core when executing any current event loop code, but potentially running between the point when the Javascript core finishes a normal event loop cycle and then starts processing the queued promise handlers. This means that code that runs nicely in Node (for example) might not work the same way due to this behaviour. Also, I also notice another thing: if JavaScript code makes a call to a native-provided method (e.g. by calling the setTimeout I show above, which I implement via a native-side handler) then during that call from JavaScript, it is possible for the native side to execute a call() and run Javascript code it wants. Again this is not what would happen in Node or Safari: it is not possible for timeouts (or network completions) to interrupt any 'builtin' function call, but in JavascriptCore it certainly is (to get around this I set a flag on the JavaScript side indicating a native call is being made, and if any native-triggered callback occurs on the javascript side when this flag is set, I have to 'queue' it via a promise handler for execution AFTER the current event loop is complete). Are these known issues with Javascript core and are there ways to get around them? thanks
0
0
50
11h
Scrolling is backwards with external devices when rotating to landscape mode
We recently converted an existing app to adopt scenes (for CarPlay). The app has one main view controller that presents a WKWebView to show our content. Everything works fine in both landscape and portait mode when swiping on the screen to scroll. But with an iPad using an external Magic Keyboard, once you rotate to landscape mode the scrolling gestures are reversed. Swiping vertically on the trackpad is scrolling the page horizontally and vice versa. When this happens an error like below is logged (this error also shows up when in portait mode, but scrolling works as expected): Unexpected window orientation: <UIWindow: 0x10370d8f0; orientation: landscapeLeft (4)> { hidden = NO; frame = {{0, 0}, {1180, 820}}; bounds = {{0, 0}, {1180, 820}}; ownsOrientation = NO; ownsOrientationTransform = NO; autorotationDisabled = NO; windowInterfaceOrientation = unknown (0); rootTransformOrientation = landscapeLeft (4); viewTransformOrientation = unknown (0); autorotationDisabled = NO; orientationVC = ... { providedSupportedOrientations = ( Pu Ll Lr Pd ); resolvedSupportedOrientations = ( Pu Ll Lr Pd ); canPreferOrientation = NO; }; }, event type: 6 It seems to suggest that while the view controller orientation is set correctly. It doesn't know what the orientation is for the window. I have been unable to figure out what would change with adopting scenes that would explain this behavior. I assume it has to do with the potential multi-window nature of it but haven't found any docs that describe how to ensure the window is setup to use the same orientation as the device. Any suggestions on things to check?
1
0
76
1d
Memory crash at String._bridgeToObjectiveCImpl()
I'll describe my crash with an example, looking for some insights into the reason why this is happening. @objc public protocol LauncherContainer { var launcher: Launcher { get } } @objc public protocol Launcher: UIViewControllerTransitioningDelegate { func initiateLaunch(url: URL, launchingHotInstance: Bool) } @objc final class LauncherContainer: NSObject, LauncherContainer, TabsContentCellTapHandler { ... init( ... ) { ... super.init() } ... // // ContentCellTapHandler // public func tabContentCellItemDidTap( tabId: String ) { ... launcher.initiateNewTabNavigation( tabId: tabId // Crash happens here ) } public class Launcher: NSObject, Launcher, FooterPillTapHandler { public func initiateNewTabNavigation(tabId: String) { ... } } public protocol TabsContentCellTapHandler: NSObject { func tabContentCellItemDidTap( tabId: String, }
2
0
92
11h
Memory crash at String._bridgeToObjectiveCImpl()
I'll describe my crash with an example, looking for some insights into the reason why this is happening. @objc public protocol LauncherContainer { var launcher: Launcher { get } } @objc public protocol Launcher: UIViewControllerTransitioningDelegate { func initiateLaunch(url: URL, launchingHotInstance: Bool) } @objc final class LauncherContainer: NSObject, LauncherContainer, TabsContentCellTapHandler { ... init( ... ) { ... super.init() } ... // // ContentCellTapHandler // public func tabContentCellItemDidTap( tabId: String ) { ... launcher.initiateNewTabNavigation( tabId: tabId // Crash happens here ) } public class Launcher: NSObject, Launcher, FooterPillTapHandler { public func initiateNewTabNavigation(tabId: String) { ... } } public protocol TabsContentCellTapHandler: NSObject { func tabContentCellItemDidTap( tabId: String, } Crash stack last 2 lines are- libswiftCore.dylib swift_unknownObjectRetain libswiftCore.dylib String._bridgeToObjectiveCImpl() String._bridgeToObjectiveCImpl() gets called when the caller and implementation is in Swift file I believe due to @objc class LauncherContainer there'd be bridging header generated. Does that mean tabId passed to tabContentCellItemDidTap is a String but the one passed to initiateNewTabNavigation is NSString? TabId is UUID().uuidString if that helps. Wondering if UUID().uuidString has something to do with this. Thanks a ton for helping. Please find attached screenshot of the stack trace.
1
0
97
14h
Calendar integers in english and alphabets in arabic
we are migrating our app to support Arabic language support but the requirement is we want the calendar/date object to display as missed. That is all the numbers in english digits and rest all the words like days, months should be in Arabic. I tried few options but at the end its resulting everything is in Arabic or in English but not the mixed as expected. Attaching the expected behavior.
1
0
83
10h
Cannot load iTunesLibrary on macOS Sequoia 15.1
I use the iTunes Library framework in one of my apps, starting with macOS Sequoia 15.1 i can't create the ITLibrary object anymore with the following error: Connection to amplibraryd was interrupted. clientName:iTunesLibrary(ITLibraryLoader) Error connecting to the server via proxy object Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.amp.library.framework" UserInfo={NSDebugDescription=connection to service named com.apple.amp.library.framework} configure failed: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.amp.library.framework" UserInfo={NSDebugDescription=connection to service named com.apple.amp.library.framework} I created a new sandboxed macOS app, added the music folder read permission and it reproduced the error: import SwiftUI import iTunesLibrary @main struct ITLibraryLoaderApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { var body: some View { Button("Load ITLibrary") { loadLibrary() } } func loadLibrary() { do { let _ = try ITLibrary(apiVersion: "1.0", options: .none) } catch { print(error) } } } I restarted my developer machine and the music app with no luck.
0
0
120
1d
When application merges libswift_concurrency.dylib is duplicated in app binary
Environment: Xcode 16.1 Swift version: 6.0.2 Inside of an Xcode project, if I declare a framework and an application. The framework is mergeable and the application merges the framework by configuring MERGE_BINARY_TYPE to Manual (or automatic it's independent). If SWIFT_VERSION is set to 6.0.X and deployment target is set to iOS 15< the build is going to fail because of this error Duplicate linked dylib '@rpath/libswift_Concurrency.dylib' in '/Users/**/Library/Developer/Xcode/DerivedData/GSPackage-dvnngsrgctfovgfbvwdlsscfycyq/Build/Products/Debug-iphonesimulator/DummyApp.app/DummyApp.debug.dylib' If I'm checking the generated artifact and inspect all of it's @rpath with otool it's giving me the following: otool -L /Users/****/Library/Developer/Xcode/DerivedData/Dummy-gbccsjwxeajftsafghxzaqksgfim/Build/Products/Debug-iphonesimulator/Dummy.app/Dummy.debug.dylib | grep @rpath @rpath/Dummy.debug.dylib (compatibility version 0.0.0, current version 0.0.0) @rpath/libswift_Concurrency.dylib (compatibility version 1.0.0, current version 0.0.0, weak) @rpath/libswift_Concurrency.dylib (compatibility version 1.0.0, current version 0.0.0, weak) A radar is already opened with the ID: FB15693702
0
0
68
2d
DocumentGroup opens an empty document on Mac Catalyst when the "Optimize for Mac" is checked
I am using a Mac Catalyst with SwiftUI for our document-based app with DocumentGroup. The issue is that when we create a new document or open an existing one, the opened view is completely blank. It is only blank/empty when the "Optimzie for Mac" is checked. If it is "Scaled t oMatch iPad", then it works well. Xcode 16.1 macOS 15.1 struct DocumentGroupTestApp: App { var body: some Scene { DocumentGroup(newDocument: WritingAppDocument()) { file in TestView() // it is empty when it gets opened. It does not work if the option "Optimize for Mac" is checked. If it is scale iPad, then it works. } } } struct TestView: View { var body: some View { Text("Hello, World!") } }
1
0
58
5h
Crashing in WKWebview Often, when the video is loaded in the webview using an HTML file
Hello, Team. We used WKWebView for our project. We loaded the HTML file into the webview and added the following configuration. weak var webView: WKWebView! func configWebView() { let webViewConfig = WKWebViewConfiguration() let controller = WKUserContentController() controller.add(self, name: "sometest") webViewConfig.userContentController = controller webViewConfig.processPool = WKProcessPool() webViewConfig.setValue(true, forKey: "allowUniversalAccessFromFileURLs") webViewConfig.mediaTypesRequiringUserActionForPlayback = [] let webpagePreferences = WKWebpagePreferences() webpagePreferences.allowsContentJavaScript = true webViewConfig.defaultWebpagePreferences = webpagePreferences webViewConfig.websiteDataStore = WKWebsiteDataStore.default() webView = WKWebView(frame: .zero, configuration: webViewConfig) webView.navigationDelegate = self webView.uiDelegate = self webView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(webView) NSLayoutConstraint.activate([ webView.topAnchor.constraint(equalTo: view.topAnchor), webView.bottomAnchor.constraint(equalTo: view.bottomAnchor), webView.leadingAnchor.constraint(equalTo: view.leadingAnchor), webView.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) loadWebView() } func loadWebView() { guard let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return } let contentFolderURL = documentsDirectoryURL.appendingPathComponent("content") let assetFolderURL = contentFolderURL.appendingPathComponent(interactiveGUID) if FileManager.default.fileExists(atPath: assetFolderURL.path) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let documentsURL = URL(fileURLWithPath: documentsPath) let fileToLoadPath = (documentsPath as NSString).appendingPathComponent("content/index_p.html") let fileURL = URL(fileURLWithPath: fileToLoadPath) autoreleasepool { DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.webView.loadFileURL(fileURL, allowingReadAccessTo: documentsURL) } } } We are experiencing webview crashes when loading an HTML file. What happened when I loaded the video file? It automatically looped. Webview frequently crashes when the HTM/JS file is loaded. When a webview crashes, the delegate method usually calls webViewWebContentProcessDidTerminate. This method calls webview.reload(). Also we are clear and cache/ deallocate eveything when i initialized those configuration mentioned as the above. Can you suggest a solution to this? Why is webview crashing? Thank you.
0
0
58
2d
How to Remove OpaqueTypeErasure from SwiftUI
I am using swiftui lately in my iOS mobile app, The Mobile app already has a pipeline that detect any experimental features and throw an error I am using swift 5 and as you all know SwiftUI is using some of OpaqueTypeErasure utility types like "some" I heard that in swift 6 the OpaqueTypeErasure is not experimental anymore But upgrading the app swift version will be a very long process Also changing the pipeline will be a very long and tiring process So i want to know if there is a way to remove OpaqueTypeErasure from SwiftUI and what is the alternatives for bypassing the error that being thrown from the pipeline
3
0
111
1d
DST, DateEncodingStrategy.iso8601, and UTC Fun
Hello, My code calls a macOS system library which returns Foundation Date properties. I have a program that will run every night, and output the data via the Swift JSONEncoder and uses DateEncodingStrategy.iso8601. As you likely know, a DST shift happened over the weekend here in the US. In my output, every single Date changed by 1 hour, despite the fact that nothing in the underlying data changed overnight. Here is an example diff in the output. I see the "Z", which I think should not be affected by DST changes. - "dateAdded" : "2003-12-15T17:02:56Z", - "dateModified" : "2007-03-07T04:31:16Z", + "dateAdded" : "2003-12-15T18:02:56Z", + "dateModified" : "2007-03-07T05:31:16Z", Here is a sample of the data: public struct Track: Codable, Hashable { var dateAdded: Date? var dateModified: Date? } And the encoding is here: extension Array where Element == Track { public func jsonData() throws -> Data { let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] encoder.dateEncodingStrategy = .iso8601 return try encoder.encode(self) } } Pretty basic stuff overall. So my questions are: Am I correct in my assumption that .iso8601 is UTC, and that UTC is daylight savings shift agnostic? Is this the right way to ensure the my JSON is encoded in UTC? If the library I am calling is building its Date incorrectly, how may I work around the problem? I'm not reporting the library name right now, in order to ensure that my code is doing the right thing without assumptions. Thanks for any tips!
3
0
98
1d
Struggling with NSScrollView
I'm still discovering swift and the various frameworks. So I'm now trying to create scrolling composition with a grid - containing images - and an NSStackView at on top. However, I'm running into a problem that might seem stupid, but when I try to wrap my NSCollectionView in another NSView and pointing the scrollView.documentView to, I can't scroll anymore... Even though it works fine when I set the scrollView.documentView to the NSCollectionView directly. Working case: override func viewDidLoad() { super.viewDidLoad() scrollView = NSScrollView(frame: .zero) scrollView.hasVerticalScroller = true scrollView.hasHorizontalScroller = false scrollView.scrollerStyle = .overlay scrollView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) vStack = NSStackView(frame: .zero) vStack.orientation = .vertical vStack.spacing = 12 * 2 vStack.translatesAutoresizingMaskIntoConstraints = false let hStack = NSStackView() hStack.orientation = .horizontal hStack.spacing = 12 hStack.translatesAutoresizingMaskIntoConstraints = false let label1 = NSTextField(labelWithString: "Collection") hStack.addArrangedSubview(label1) let layout = PinterestLayout() layout.delegate = self collectionView = NSCollectionView(frame: .zero) collectionView.collectionViewLayout = layout collectionView.dataSource = self collectionView.delegate = self collectionView .register( ArtCardCell.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier("ArtCardCell") ) collectionView.backgroundColors = [.BG] collectionView.translatesAutoresizingMaskIntoConstraints = false // vStack.addArrangedSubview(hStack) // vStack.addArrangedSubview(collectionView) scrollView.documentView = collectionView NSLayoutConstraint.activate([ scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), scrollView.topAnchor.constraint(equalTo: view.topAnchor), scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor), // vStack.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), // vStack.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor), // vStack.topAnchor.constraint(equalTo: scrollView.topAnchor), // vStack.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor), // vStack.widthAnchor.constraint(equalTo: scrollView.widthAnchor), collectionView.widthAnchor.constraint(equalTo: scrollView.widthAnchor), // vStack.arrangedSubviews[0].leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 12), // vStack.arrangedSubviews[0].trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -12), // vStack.arrangedSubviews[0].topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 80) ]) collectionView.postsBoundsChangedNotifications = true NotificationCenter.default.addObserver(self, selector: #selector(didScroll(_:)), name: NSView.boundsDidChangeNotification, object: collectionView.enclosingScrollView?.contentView ) } collectionView height: 3549.0 ScrollView height: 628.0 StackView height: -- Dysfunctional case: override func viewDidLoad() { super.viewDidLoad() scrollView = NSScrollView(frame: .zero) scrollView.hasVerticalScroller = true scrollView.hasHorizontalScroller = false scrollView.scrollerStyle = .overlay scrollView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) vStack = NSStackView(frame: .zero) vStack.orientation = .vertical vStack.spacing = 12 * 2 vStack.translatesAutoresizingMaskIntoConstraints = false let hStack = NSStackView() hStack.orientation = .horizontal hStack.spacing = 12 hStack.translatesAutoresizingMaskIntoConstraints = false let label1 = NSTextField(labelWithString: "Collection") hStack.addArrangedSubview(label1) let layout = PinterestLayout() layout.delegate = self collectionView = NSCollectionView(frame: .zero) collectionView.collectionViewLayout = layout collectionView.dataSource = self collectionView.delegate = self collectionView .register( ArtCardCell.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier("ArtCardCell") ) collectionView.backgroundColors = [.BG] collectionView.translatesAutoresizingMaskIntoConstraints = false vStack.addArrangedSubview(hStack) vStack.addArrangedSubview(collectionView) scrollView.documentView = vStack NSLayoutConstraint.activate([ scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), scrollView.topAnchor.constraint(equalTo: view.topAnchor), scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor), vStack.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), vStack.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor), vStack.topAnchor.constraint(equalTo: scrollView.topAnchor), vStack.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor), vStack.widthAnchor.constraint(equalTo: scrollView.widthAnchor), collectionView.widthAnchor.constraint(equalTo: scrollView.widthAnchor), vStack.arrangedSubviews[0].leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 12), vStack.arrangedSubviews[0].trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -12), vStack.arrangedSubviews[0].topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 80) ]) } collectionView height: 508.0 ScrollView height: 628.0 StackView height: 628.0
0
0
51
3d
How can we make elements which are grouped accessible for automation
I have a stackview which have 2 labels class TextView: UIView { @IBOutlet private weak var stackView: UIStackView! { didSet { stackView.isAccessibilityElement = true stackView.accessibilityLabel = label1.text + label2.text } } @IBOutlet private weak var label1: UILabel! { didSet { label1.accessibilityIdentifier = "label1" } } @IBOutlet private weak var: UILabel!{ didSet { label2.accessibilityIdentifier = "label2" } } } My goal here is to have a combines accessibility label for the stackview and yet able to access the accessibilityIdentifier of child elements for automation.
0
0
273
3d