Swift Packages

RSS for tag

Create reusable code, organize it in a lightweight way, and share it across Xcode projects and with other developers using Swift Packages.

Posts under Swift Packages tag

163 Posts

Post

Replies

Boosts

Views

Activity

Xcode 16.4 fails to build swift packages.
After updating to Xcode 16.4, Package resolution fails with some cryptic errors. Each package fails with the following message Showing Recent Errors Only <unknown>:0: warning: legacy driver is now deprecated; consider avoiding specifying '-disallow-use-new-driver' <module-includes>:200:9: note: in file included from <module-includes>:200: 198 | #import "mach/mach_traps.h" 199 | #import "mach/mach_types.h" 200 | #import "mach/mach_vm.h" | `- note: in file included from <module-includes>:200: 201 | #import "mach/mach_voucher.h" 202 | #import "mach/mach_voucher_types.h" /Applications/Xcode-16.4.0.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX15.4.sdk/usr/include/mach/mach_vm.h:436:2: error: unknown type name 'mach_vm_offset_list_t'; did you mean 'mach_vm_offset_t'? 434 | ( 435 | vm_map_t target, 436 | mach_vm_offset_list_t in_pointer_list, | `- error: unknown type name 'mach_vm_offset_list_t'; did you mean 'mach_vm_offset_t'? 437 | mach_msg_type_number_t in_pointer_listCnt, 438 | mach_vm_offset_list_t out_pointer_list, /Applications/Xcode-16.4.0.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX15.4.sdk/usr/include/mach/arm/vm_types.h:108:33: note: 'mach_vm_offset_t' declared here 106 | 107 | typedef uint64_t mach_vm_address_t __kernel_ptr_semantics; 108 | typedef uint64_t mach_vm_offset_t __kernel_ptr_semantics; | `- note: 'mach_vm_offset_t' declared here 109 | typedef uint64_t mach_vm_size_t; 110 | <module-includes>:200:9: note: in file included from <module-includes>:200: 198 | #import "mach/mach_traps.h" 199 | #import "mach/mach_types.h" 200 | #import "mach/mach_vm.h" | `- note: in file included from <module-includes>:200: 201 | #import "mach/mach_voucher.h" 202 | #import "mach/mach_voucher_types.h" <unknown>:0: error: could not build Objective-C module 'Darwin' /Applications/Xcode-16.4.0.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX15.4.sdk/usr/include/mach/mach_vm.h:438:2: error: unknown type name 'mach_vm_offset_list_t'; did you mean 'mach_vm_offset_t'? 436 | mach_vm_offset_list_t in_pointer_list, 437 | mach_msg_type_number_t in_pointer_listCnt, 438 | mach_vm_offset_list_t out_pointer_list, | `- error: unknown type name 'mach_vm_offset_list_t'; did you mean 'mach_vm_offset_t'? 439 | mach_msg_type_number_t *out_pointer_listCnt 440 | ); /Applications/Xcode-16.4.0.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX15.4.sdk/usr/include/mach/arm/vm_types.h:108:33: note: 'mach_vm_offset_t' declared here 106 | 107 | typedef uint64_t mach_vm_address_t __kernel_ptr_semantics; 108 | typedef uint64_t mach_vm_offset_t __kernel_ptr_semantics; | `- note: 'mach_vm_offset_t' declared here 109 | typedef uint64_t mach_vm_size_t; 110 | /Users/paulwilliamson/Developer/ios-app/Packages/Modules/ModalAdvert/Package.swift:4:8: error: failed to build module 'PackageDescription' for importation due to the errors above; the textual interface may be broken by project issues or a compiler bug 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription | `- error: failed to build module 'PackageDescription' for importation due to the errors above; the textual interface may be broken by project issues or a compiler bug 5 | 6 | let package = Package( We don't specify -disallow-use-new-driver, so I'm unsure where that message comes from. We have cleared derived data and are performing a clean build.
0
1
245
May ’25
Objective-C headers build fine with swift but not with Xcode
On my M4 Mac running macOS 15.5 using Xcode 16.4 & Xcode CLT 16.4, Swift code in my Swift Package Manager 5.9 project (https://github.com/mas-cli/mas) builds fine against some included Objective-C headers via the following command line: swift build -c release But cannot find modules for the included Objective-C headers when building inside Xcode 16.4 or with the following command line on the same Mac: xcodebuild -scheme mas -configuration Release -destination platform=macOS,arch=arm64,variant=macos The error is: Sources/mas/AppStore/AppleAccount.swift:9:16: error: no such module 'StoreFoundation' How can I get Xcode / xcodebuild to work? Note that the project is normally built by running: Scripts/build which runs: swift build -c release after running the following script, which must be run before any build (swift, Xcode, or xcodebuild) because it generates a necessary file (Sources/mas/Package.swift): Scripts/generate_package_swift I've tried moving the Objective-C headers into include subfolders of their existing module folders, using double quotes instead of angle brackets for the #import statements, having module.modulemap files in the include subfolders or their parent module folder, and moving the module folders one level up the file hierarchy, to no avail. I've also tried various changes to the root-level Package.swift (not the generated one deeper in the hierarchy, which isn't inclined in the build configuration), like making separate library targets for each of the Objective-C modules, various swiftSettings & linkerSettings, etc. Maybe some of those changes would have helped, but maybe they were in incorrect combinations. Thanks for any help.
0
0
122
May ’25
Room Plan Issue (structure.capturedStructure)
Hi everyone, My app crashed when using the merge room feature. I suspect the issue might be caused by a wall having more than 4 edges. Has anyone experienced a similar problem and found a solution? I’d really appreciate any advice or suggestions. Thank you all, and have a great day! let capturedStructure = try await structure.capturedStructure(from: self.rooms)
2
1
184
May ’25
Binary Signing Error
I will post my app xyz.app uses XY swift package this swift package is a wrapper for XYSDK.xcframework XYSDK.xcframework written in c++ and app running on arm64 macos and iphones succesfully. I got this error when i want to distribute it. Currently i sign .framework for ios with Apple Distribution Certificate and same certificate for macos framework there is no other signing step for swift package or xcframework other than that when i want to archive it validates succesfully. Exporting step shows that app has signed, has provisining profile. but .framework is only signed has no provisioning profile. Also one point i see: i have one target named xyz and its Frameworks, Lİbraries and Embedded Context has only XY package but Embed part has no option like embed and sign etc. Blank. I need more info about what am i doing wrong in which step ? I am stuck and can not move any further like weeks Error Detail: Invalid Signature. The binary with bundle identifier XYSDK at path “xyz.app/Frameworks/XYSDK.framework” contains an invalid signature. Make sure you have signed your application with a distribution certificate, not an ad hoc certificate or a development certificate. Verify that the code signing settings in Xcode are correct at the target level (which override any values at the project level). Additionally, make sure the bundle you are uploading was built using a Release target in Xcode, not a Simulator target. If you are certain your code signing settings are correct, choose “Clean All” in Xcode, delete the “build” directory in the Finder, and rebuild your release target. For more information, please consult https://developer.apple.com/support/code-signing. (90035)
1
0
134
May ’25
Xcode does not see code changes in local Swift packages (autocomplete wrong, errors shown, but still compiles)
Hey, I've been having a lot of problems with Xcode 16 not seeing changes made to code in local Swift packages (the packages are inside the root directory of the project). Whenever I make any change like renaming a variable or type, or adding new methods or whatever, autocomplete doesn't see those changes and when I type in that new type/variable manually it gives me an error. However, building the project still works fine, even with the errors never going away. The only way for it to notice the code changes is to clean the project and build it again which takes a long time. At first, I thought this was connected to the new "Explicitly built modules" feature in Xcode 16, but I turned it off and it still happens. Any ideas what I can try? I'm on the latest Xcode version, but this problem has been happening since Xcode 16 originally came out. Thanks! Dennis
0
0
134
May ’25
Granting Microphone Access through in-app authorisation request on the VisionOS 2.4 Simulator causes it to crash
When requesting authorisation to gain access to the user's microphone in the visionOS 2.4 simulator, the simulator crashes upon the user clicking allow. Using Swift 6, code below. Bug Report: FB17667361 @MainActor private func checkMicrophonePermission() async { logger.debug("Checking microphone permissions...") // Get the current permission status let micAuthStatus = AVAudioApplication.shared.recordPermission logger.debug("Current Microphone permission status: \(micAuthStatus.rawValue)") if micAuthStatus == .undetermined { logger.info("Requesting microphone authorization...") // Use structured concurrency to wait for permission result let granted = await withCheckedContinuation { continuation in AVAudioApplication.requestRecordPermission() { allowed in continuation.resume(returning: allowed) } } logger.debug("Received microphone permission result: \(granted)") // Convert to SFSpeechRecognizerAuthorizationStatus for consistency let status: SFSpeechRecognizerAuthorizationStatus = granted ? .authorized : .denied // Handle the authorization status handleAuthorizationStatus(status: status, type: "Microphone") // If granted, configure audio session if granted { do { try await configureAudioSession() } catch { logger.error("Failed to configure audio session after microphone authorization: \(error.localizedDescription)") self.isAvailable = false self.processingError = .audioSessionError(description: "Failed to configure audio session after microphone authorization") } } } else { // Convert to SFSpeechRecognizerAuthorizationStatus for consistency let status: SFSpeechRecognizerAuthorizationStatus = (micAuthStatus == .granted) ? .authorized : .denied handleAuthorizationStatus(status: status, type: "Microphone") // If already granted, configure audio session if micAuthStatus == .granted { do { try await configureAudioSession() } catch { logger.error("Failed to configure audio session for existing microphone authorization: \(error.localizedDescription)") self.isAvailable = false self.processingError = .audioSessionError(description: "Failed to configure audio session for existing microphone authorization") } } } }
1
1
125
May ’25
ForEach and RandomAccessCollection
I'm trying to build a custom FetchRequest that I can use outside a View. I've built the following ObservableFetchRequest class based on this article: https://augmentedcode.io/2023/04/03/nsfetchedresultscontroller-wrapper-for-swiftui-view-models @Observable @MainActor class ObservableFetchRequest&lt;Result: Storable&gt;: NSObject, @preconcurrency NSFetchedResultsControllerDelegate { private let controller: NSFetchedResultsController&lt;Result.E&gt; private var results: [Result] = [] init(context: NSManagedObjectContext = .default, predicate: NSPredicate? = Result.E.defaultPredicate(), sortDescriptors: [NSSortDescriptor] = Result.E.sortDescripors) { guard let request = Result.E.fetchRequest() as? NSFetchRequest&lt;Result.E&gt; else { fatalError("Failed to create fetch request for \(Result.self)") } request.predicate = predicate request.sortDescriptors = sortDescriptors controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) super.init() controller.delegate = self fetch() } private func fetch() { do { try controller.performFetch() refresh() } catch { fatalError("Failed to fetch results for \(Result.self)") } } private func refresh() { results = controller.fetchedObjects?.map { Result($0) } ?? [] } var predicate: NSPredicate? { get { controller.fetchRequest.predicate } set { controller.fetchRequest.predicate = newValue fetch() } } var sortDescriptors: [NSSortDescriptor] { get { controller.fetchRequest.sortDescriptors ?? [] } set { controller.fetchRequest.sortDescriptors = newValue.isEmpty ? nil : newValue fetch() } } internal func controllerDidChangeContent(_ controller: NSFetchedResultsController&lt;any NSFetchRequestResult&gt;) { refresh() } } Till this point, everything works fine. Then, I conformed my class to RandomAccessCollection, so I could use in a ForEach loop without having to access the results property. extension ObservableFetchRequest: @preconcurrency RandomAccessCollection, @preconcurrency MutableCollection { subscript(position: Index) -&gt; Result { get { results[position] } set { results[position] = newValue } } public var endIndex: Index { results.endIndex } public var indices: Indices { results.indices } public var startIndex: Index { results.startIndex } public func distance(from start: Index, to end: Index) -&gt; Int { results.distance(from: start, to: end) } public func index(_ i: Index, offsetBy distance: Int) -&gt; Index { results.index(i, offsetBy: distance) } public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -&gt; Index? { results.index(i, offsetBy: distance, limitedBy: limit) } public func index(after i: Index) -&gt; Index { results.index(after: i) } public func index(before i: Index) -&gt; Index { results.index(before: i) } public typealias Element = Result public typealias Index = Int } The issue is, when I update the ObservableFetchRequest predicate while searching, it causes a Index out of range error in the Collection subscript because the ForEach loop (or a List loop) access a old version of the array when the item property is optional. List(request, selection: $selection) { item in VStack(alignment: .leading) { Text(item.content) if let information = item.information { // here's the issue, if I leave this out, everything works Text(information) .font(.callout) .foregroundStyle(.secondary) } } .tag(item.id) .contextMenu { if Item.self is Client.Type { Button("Editar") { openWindow(ClientView(client: item as! Client), id: item.id!) } } } } Is it some RandomAccessCollection issue or a SwiftUI bug?
0
0
140
May ’25
Objective-C Literals inside a Swift Package
I have a Swift Package that contains an Objective-C target. The target contains Objective-C literals but unfortunately the compiler says "Initializer element is not a compile-time constant", what am I doing wrong? Based on the error triggering in the upper half, I take it that objc_array_literals is on. My target definition looks like: .target( name: "MyTarget", path: "Sources/MySourcesObjC", publicHeadersPath: "include", cxxSettings: [ .unsafeFlags("-fobjc-constant-literals") ] ), I believe Objective-C literals are enabled since a long time but I still tried passing in the -fobjc-constant-literals flag and no luck. To be clear I'm not interested in a run-time initialization, I really want it to be compile time. Does anyone know what I can do?
3
0
232
May ’25
Xcode 16.0 syntax highlighting and autocompletion is broken for Swift packages with .binaryTarget
Syntax highlighting & code autocompletion is broken for Swift Packages wrapping an underlying binary target. Jump to defenition for module import shows the whole module interface and project builds & archives just fine, but any known workarounds to resurrect syntax assistant won't work without any errors/warnings. Replacing the .binaryTarget() with plain .target() with source code in package dependency brings all assistant features back. Steps to reproduce (project attached): Create a local Swift Package Add a dependency with binary target (for example — AppsFlyerFramework https://github.com/AppsFlyerSDK/AppsFlyerFramework) Try to use dependency product with binary dependency Attempted steps to fix: Full DD clean Full project clean ~15 min to index Xcode 16.0 & Sonoma 14.6.1, problem persists with Xcode16.2 & Sequoia. Radar #16035437
1
1
396
May ’25
Suggestions on macOS and iPad app structure
Building an app to edit the various parameters of digital musical instruments. A typical user would have perhaps max 6 instruments, out of the hundreds of possibilities. Would like to structure the app with a global window, menu, etc which would be a free download. The user could download editor inserts for their particular set of instruments and ignore all of the others. The downloaded editors would show as options in a menu. It seem like more than a widget but less than a library. Building a monolithic app containing all possible editors doesn't seem like an option, but separate full-app editors for each piece of gear doesn't sound right either. Any suggestions out there? Thanks very much Brian
0
0
120
May ’25
Xcode 13 "Missing package product" using local Swift Packages
I have a project I've been working off of for a few years now that makes use of local Swift Packages. In my workspace, I have a "Kit" project that generates a framework using several local Swift Packages as dependencies. In Xcode 12, the local Swift packages resolve correctly and compiles, but each beta of Xcode 13 gives me the error: "[ProjectName].xcodeproj Missing package product '[LocalSwiftPackage]'" Clearing the package cache, derived data, or restarting the application does not resolve the issue. Only Swift Packages that are remotely loaded from a URL are compiled correctly. Using local packages to separate module code, while still being able to edit in the same project, has been essential to my workflow and would hate to see Xcode 13 release with these breaking changes, and I have not seen this issue listed in the known issues for the Xcode 13 release notes. Has anyone else experienced this issue or found a workaround?
20
14
84k
May ’25
SwiftUI FileManager MacOS moving a file
Until a few days ago, I had a bit of code that could download a file from elsewhere to my home drive, "Users/eric". Today, the code downloads the file to "locat", but the following no longer works let _ = try fileManager.copyItem(atPath: locat, toPath: "/Users/eric/file.txt" ) After a careful search, I've changed the network to allow Network connections, and set User Selected and Downloads Folder to Read/Write without any luck. I am using Catalina and SwiftUI on a recent Mac (2023). As well, it was working just a few days ago. Any ideas or pointers?
1
0
113
May ’25
Followed docs for "Local Package", how to add to 2nd project?
I have a couple apps in one git repository. I'd like to have a Swift package in that repo as well, shared by apps. In other words, I don't want a separate repo for the Swift package. I followed the instructions here: https://developer.apple.com/documentation/xcode/organizing-your-code-with-local-packages It seems to work. I can write code like this in my app: import MyLocalPackage func foo() { myLocalPackageFunc() } I notice that the package is not listed under Project > MyApp > Package Dependencies. I don't really care, as long as I can reuse code between apps. But when I try to add this package code to a 2nd app, I'm at a loss. I tried "Add Package Dependencies" and "Add Local", but that creates a different looking setup than the 1st app. The code is browsable in the project navigator. And when I try to build it says "Missing package product 'MyLocalPackage'. The documentation linked above, which I used for the 1st app, does a "New > Package". I don't want a new package. How can I connect the existing one?
0
0
76
May ’25
Xcode Cloud randomly fails to resolve package dependencies
Hi folks, I've been having this issue for the last few months, where Xcode Cloud fails to resolve Swift package dependencies while compiling my builds, seemingly at random. Some of my Xcode Cloud builds will fail after several minutes, with an error log looking like that : xcodebuild: error: Could not resolve package dependencies: failed downloading 'https://dl.google.com/firebase/ios/bin/grpc/1.62.2/rc0/grpcpp.zip' which is required by binary target 'grpcpp': downloadError("The request timed out.") Whenever this happens, I have to manually restart an Xcode Cloud build process (or several builds, since the error can happen multiple times in a row), to the point it's becoming increasingly painful to rely on Xcode Cloud for my workflow. The failing packages are mostly random (meaning, it's not always the same one that Xcode fails to resolve), but they are always publicly accessible, even though I have an environment variable set in my Xcode workflows to retrieve a single Github private dependency (maybe this has some kind of importance). Could anyone tell me if this is an isolated issue, or if I could do anything on my end to resolve this ? Thank you !
7
2
1.3k
Apr ’25
Issue: Chart Scroll Not Working in iOS 18 with Chart Overlay Tap Gesture
Summary I have a SwiftUI Chart that worked correctly in iOS 17, allowing both horizontal scrolling and tap gesture selection. However, in iOS 18, the same exact chart will not allow for both tap gestures and scrolling to work -- it's either we allow scrolling or we allow tap gestures but not both. We have tried everything to try to circumvent this issue but have had to resort to old methods of creating the chart. This is an issue that has negatively impacted our customers as well. Again, the charts were working fine on iOS 17, but on iOS 18 the chart scroll + tap gesture capability is not working. Expected Behavior (iOS 17) Users can scroll horizontally through the chart. Users can tap on data points to highlight them. The selected data point updates when tapped. Observed Behavior (iOS 18) The chart no longer scrolls when chartOverlay with the Tap Gesture is applied. Tap selection still works as expected. Code Snippet Below is the working implementation from iOS 17: private var iOS17ChartView: some View { Chart { RectangleMark( yStart: .value(String(firstLevelAlertBand), firstLevelAlertBand), yEnd: .value("100", 100) ) .foregroundStyle(Theme.Colors.green.opacity(0.15)) RectangleMark( yStart: .value(String(secondLevelAlertBand), secondLevelAlertBand), yEnd: .value(String(firstLevelAlertBand), firstLevelAlertBand) ) .foregroundStyle(Theme.Colors.orange.opacity(0.15)) RectangleMark( yStart: .value("0", 0), yEnd: .value(String(secondLevelAlertBand), secondLevelAlertBand) ) .foregroundStyle(Theme.Colors.red.opacity(0.15)) ForEach(telemetryData, id: \.timestamp) { entry in if let utcDate = dateFormatter.date(from: entry.timestamp) { let localDate = convertToUserTimeZone(date: utcDate) let tankLevel = entry.tankLevel ?? 0 LineMark( x: .value("Date", localDate), y: .value("Tank Level", tankLevel) ) .foregroundStyle(statusColor) AreaMark( x: .value("Date", localDate), y: .value("Tank Level", tankLevel) ) .foregroundStyle(statusColor.opacity(0.50)) PointMark( x: .value("Date", localDate), y: .value("Tank Level", tankLevel) ) .foregroundStyle(selectedDataPoint?.date == localDate ? Theme.Colors.primaryColor : statusColor) .symbolSize(selectedDataPoint?.date == localDate ? 120 : 80) PointMark( x: .value("Date", localDate), y: .value("Tank Level", tankLevel) ) //.foregroundStyle(.white).symbolSize(10) .foregroundStyle(Theme.Colors.white(colorScheme: colorScheme)) .symbolSize(12) } } } .chartXScale(domain: (firstTimestamp ?? Date())...(latestTimestamp ?? Date())) .chartXVisibleDomain(length: visibleDomainSize) .chartScrollableAxes(.horizontal) .chartScrollPosition(x: $chartScrollPositionX) .chartXAxis { AxisMarks(values: .stride(by: xAxisStrideUnit, count: xAxisCount())) { value in if let utcDate = value.as(Date.self) { let localDate = convertToUserTimeZone(date: utcDate) let formatStyle = self.getFormatStyle(for: interval) AxisValueLabel { Text(localDate, format: formatStyle) .font(Theme.Fonts.poppinsRegularExtraSmall) .foregroundStyle(Theme.Colors.black(colorScheme: colorScheme)) } AxisTick() .foregroundStyle(Theme.Colors.black(colorScheme: colorScheme).opacity(1)) } } } .chartOverlay { proxy in GeometryReader { geometry in Rectangle().fill(Color.clear).contentShape(Rectangle()) .onTapGesture { location in let xPosition = location.x - geometry[proxy.plotAreaFrame].origin.x // Use proxy to get the x-axis value at the tapped position if let selectedDate: Date = proxy.value(atX: xPosition) { if let closestEntry = telemetryData.min(by: { abs(dateFormatter.date(from: $0.timestamp)!.timeIntervalSince1970 - selectedDate.timeIntervalSince1970) < abs(dateFormatter.date(from: $1.timestamp)!.timeIntervalSince1970 - selectedDate.timeIntervalSince1970) }) { selectedDataPoint = (convertToUserTimeZone(date: dateFormatter.date(from: closestEntry.timestamp)!), closestEntry.tankLevel ?? 0) if let dateXPos = proxy.position(forX: convertToUserTimeZone(date: dateFormatter.date(from: closestEntry.timestamp)!)), let tankLevelYPos = proxy.position(forY: closestEntry.tankLevel ?? 0) { // Offset the x-position based on the scroll position let adjustedXPos = dateXPos - proxy.position(forX: chartScrollPositionX)! withAnimation(.spring()) { selectedPointLocation = CGPoint(x: adjustedXPos, y: tankLevelYPos - 60) // Offset popup above the point showPopup = true } } } } } } .onChange(of: chartScrollPositionX) { newValue in // Dynamically update the popup position when scroll changes if let selectedDataPoint = selectedDataPoint { if let dateXPos = proxy.position(forX: selectedDataPoint.date) { let adjustedXPos = dateXPos - proxy.position(forX: chartScrollPositionX)! selectedPointLocation.x = adjustedXPos } } } } } Please help! Nick
1
1
560
Apr ’25
GADMobile not identifying
Hi, first time question. I have a game app that I am trying to include google ads on: import GoogleMobileAds I have the following bit of code: init() { GADMobileAds.sharedInstance().start(completionHandler: { _ in print("✅ AdMob started successfully") }) } That is throwing the following error: OliviasGameApp.swift:9:22 Cannot call value of non-function type 'MobileAds' I have gone through countless troubleshooting, including transitioning to Pods. Is there any help on what I can do to resolve this issue?
2
0
81
Apr ’25