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

200 Posts

Post

Replies

Boosts

Views

Activity

CoreData in Swift Packages
I am having issues loading my model from a Swift Package with the following structure: | Package.swift | Sources | - | SamplePackage | - | - Core | - | - | - SamplePackageDataStack.swift | - | - | - DataModel.xcdatamodeld | - | - | - | - Model.xcdatamodel ( <- is this new? ) As mentioned, I am not required to list the xcdatamodeld as a resource in my Package manifest. When trying to load the model in the main app, I am getting CoreData: error:  Failed to load model named DataModel Code: In my swift Package: public class SamplePackageDataStack: NSObject {     public static let shared = SamplePackageDataStack()     private override init() {}     public lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "DataModel") container.loadPersistentStores(completionHandler: { (storeDescription, error) in             if let error = error as NSError? {                 fatalError("Unresolved error \(error), \(error.userInfo)")             }         })         return container     }()     /// The managed object context associated with the main queue. (read-only)     public var context: NSManagedObjectContext {         return self.persistentContainer.viewContext     }     public func saveContext () {         if context.hasChanges {             do {                 try context.save()             } catch {                 let nserror = error as NSError                 fatalError("Unresolved error \(nserror), \(nserror.userInfo)")             }         }     } } Main App: import SamplePackage class ViewController: UIViewController { override func viewDidLoad() { &#9;&#9;&#9;&#9;&#9;super.viewDidLoad() &#9;var container = SamplePackageDataStack.shared.persistentContainer         print(container) &#9;&#9;} }
5
0
5.5k
Jul ’25
Entities moved with Manipulation Component in visionOS Beta 4 are clipped by volume bounds
In Beta 1,2, and 3, we could pick up and inspect entities, bringing them closer while moving them outside of the bounds of a volume. As of Beta 4, these entities are now clipped by the bounds of the volume. I'm not sure if this is a bug or an intended change, but I files a Feedback report (FB19005083). The release notes don't mention a change in behavior–at least not that I can find. Is this an intentional change or a bug? Here is a video that shows the issue. https://youtu.be/ajBAaSxLL2Y In the previous versions of visionOS 26, I could move these entities out of the volume and inspect them close up. Releasing would return them to the volume. Now they are clipped as soon as they reach the end of the volume. I haven't had a chance to test with windows or with the SwiftUI modifier version of manipulation.
1
4
358
Jul ’25
Autofill Extension can't find bundle while the main app can
I have a Swift Package, it's added to both the main app and the autofill extension. The main app is an iOS app that run directly on my mac from Xcode. I use this extension to access the bundle import Foundation import OSLog class CurrentBundleFinder {} extension Foundation.Bundle { static let myModule: Bundle = { /* The name of your local package, prepended by "LocalPackages_" */ let bundleName = "DesignSystem_DesignSystem" let logger = Logger(subsystem: "DesignSystem", category: "Bundle") logger.error("Searching for bundle: \(bundleName)") let candidates = [ /* Bundle should be present here when the package is linked into an App. */ Bundle.main.resourceURL, /* Bundle should be present here when the package is linked into a framework. */ Bundle(for: CurrentBundleFinder.self).resourceURL, /* For command-line tools. */ Bundle.main.bundleURL, /* Bundle should be present here when running previews from a different package (this is the path to "…/Debug-iphonesimulator/"). */ Bundle(for: CurrentBundleFinder.self).resourceURL?.deletingLastPathComponent().deletingLastPathComponent(), /* For app extensions - look in parent app bundle */ Bundle.main.bundleURL.deletingLastPathComponent().deletingLastPathComponent(), ] logger.error("all bundle: \(candidates, privacy: .public)") for (index, candidate) in candidates.enumerated() { logger.error("Checking candidate \(index): \(candidate?.absoluteString ?? "nil", privacy: .public)") let bundlePath = candidate?.appendingPathComponent(bundleName + ".bundle") logger.error("Bundle path: \(bundlePath?.absoluteString ?? "nil", privacy: .public)") if let bundle = bundlePath.flatMap(Bundle.init(url:)) { logger.error("Successfully found bundle at: \(bundlePath?.absoluteString ?? "unknown", privacy: .public)") return bundle } } logger.error("Unable to find bundle named \(bundleName)") fatalError("unable to find bundle named \(bundleName)") }() } Bellow is the log from the main app and the autofill extension log.txt I have check that /private/var/folders/cb/fctmx0_x3_dbxy_9wnm7g0s40000gn/X/1CC84EBB-DAC0-5120-9346-5EFBC8691CF1/d/Wrapper/Proton Pass.app/PlugIns/AutoFill.appex/DesignSystem_DesignSystem.bundle exist in the file system, but the autofill extension is unable to create a bundle from that
1
0
82
Jul ’25
Windows-specific timeout issue with URLSession in Swift (Error Code -1001)
Hello everyone, 👋🏼🤠 I've been struggling with a persistent issue for several weeks and would greatly appreciate any insights or suggestions from the community. ❗️Problem Summary We are sending JSON requests (~100 KB in size) via URLSession from a Swift app running on Windows. These requests consistently time out after a while. Specifically, we receive the following error: Error Domain=NSURLErrorDomain Code=-1001 "(null)" This only occurs on Windows – under macOS and Linux, the same requests work perfectly. 🔍 Details The server responds in under 5 seconds, and we have verified that the backend (a Vapor app in Kubernetes) is definitely not the bottleneck. The request always hits the timeout interval, no matter how high we configure it: 60, 120, 300, 600 seconds – the error remains the same. (timeoutForRequest) The request flow: Swift App (Windows) ---> HTTPS ---> Load Balancer (NGINX) ---> HTTP ---> Ingress Controller ---> Vapor App (Kubernetes) On the load balancer we see this error: client prematurely closed connection, so upstream connection is closed too (104: Connection reset by peer) The Ingress Controller never receives the complete body in these error cases. The content length set by the Swift app exceeds the data actually received. We disabled request buffering in the Ingress Controller, but the issue persists. We even tested a setup where we inserted a Caddy server in between to strip away TLS. The Swift app sent unencrypted HTTP requests to Caddy, which then forwarded them. This slightly improved stability but did not solve the issue. 🧪 Additional Notes The URLSession is configured in an actor, with a nonisolated URLSession instance: actor DataConnectActor { nonisolated let session : URLSession = URLSession(configuration: { let urlSessionConfiguration : URLSessionConfiguration = URLSessionConfiguration.default urlSessionConfiguration.httpMaximumConnectionsPerHost = ProcessInfo.processInfo.environment["DATACONNECT_MAX_CONNECTIONS"]?.asInt() ?? 16 urlSessionConfiguration.timeoutIntervalForRequest = TimeInterval(ProcessInfo.processInfo.environment["DATACONNECT_REQUEST_TIMEOUT"]?.asInt() ?? 120) urlSessionConfiguration.timeoutIntervalForResource = TimeInterval(ProcessInfo.processInfo.environment["DATACONNECT_RESSOURCE_TIMEOUT"]?.asInt() ?? 300) urlSessionConfiguration.httpAdditionalHeaders = ["User-Agent": "DataConnect Agent (\(Environment.version))"] return urlSessionConfiguration }()) public internal(set) var accessToken: UUID? = nil ... } Requests are sent via a TaskGroup, limited to 5 concurrent tasks. The more concurrent tasks we allow, the faster the timeout occurs. We already increased the number of ephemeral ports in Windows. This made things slightly better, but the problem remains. Using URLSessionDebugLibcurl=1 doesn't reveal any obvious issue related to libcurl. We have also implemented a retry mechanism, but all retries also time out. 🔧 Request Flow (Code Snippet Summary) let data = try JSONEncoder().encode(entries) var request = URLRequest(url: url) request.httpMethod = "POST" request.httpBody = data request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type") // additional headers... let (responseData, response) = try await urlSession.data(for: request) ✅ What We’ve Tried Tested with and without TLS Increased timeout and connection settings Disabled buffering on Ingress Increased ephemeral ports on Windows Limited concurrent requests Used URLSessionDebugLibcurl=1 We don't know how we can look any further here. Thank you in advance for any guidance!
2
0
190
Jul ’25
Module compiled with Swift 6.0.3 cannot be imported by the Swift 6.1 compiler
Module compiled with Swift 6.0.3 cannot be imported by the Swift 6.1 compiler: /private/var/tmp/_bazel_xx/8b7c61ad484d9da1bf94a11f12ae6ffd/rules_xcodeproj.noindex/build_output_base/execroot/main/CustomModules/BIYThred/CocoaLumberjack/framework/CocoaLumberjack.framework/Modules/CocoaLumberjack.swiftmodule/arm64-apple-ios.swiftmodule
1
0
700
Jul ’25
TabView + NavigationStack + ScrollView navigationTitle bug
Hello there! I've been struggline with this thing for a two days now, and seems like it's a bug in SwiftUI. Navigation title is jumping on top of the ScrollView's content when switching tabs in TabView. Steps to reproduce: Scroll one tab to the bottom so that the large title is hidden and the floating toolbar appears. Go to another tab in the tab bar. Go back to the initial tab (it is still scrolled), and press the current tab button again to scroll to the top. The navigation title will glitch and be on top of the content. The animation fixes if you scroll again manually. Video: https://share.cleanshot.com/PFCSKMlH Code (simplified): import SwiftData import SwiftUI @main struct MyApp: App { var body: some Scene { WindowGroup { TabsContentView() } } } // ... struct TabsContentView: View { enum Tab { case library, profile } @State private var selectedTab: Tab = .library var body: some View { TabView(selection: $selectedTab) { NavigationStack { YourLibraryList() .navigationTitle("Your Library") } .tabItem { Label("Library", systemImage: "tray.fill") } .tag(Tab.library) NavigationStack { VStack { Spacer() Text("Profile") .font(.largeTitle) .foregroundColor(Color.theme.text) Text("Manage your account and preferences here") .font(.body) .foregroundColor(Color.theme.mutedForeground) .multilineTextAlignment(.center) .padding(.horizontal) Spacer() } .navigationTitle("Explore") } .tabItem { Label("Profile", systemImage: "person.fill") } .tag(Tab.profile) } .toolbarBackground(.ultraThinMaterial, for: .tabBar) .toolbarBackground(.visible, for: .tabBar) } } // ... struct YourLibraryList: View { var body: some View { ScrollView { VStack(spacing: 12) { ForEach(1 ... 20, id: \.self) { number in RoundedRectangle(cornerRadius: 12) .fill(Color.blue.opacity(0.1)) .stroke(Color.blue, lineWidth: 1) .frame(height: 60) .overlay( Text("\(number)") .font(.title2) .fontWeight(.semibold) .foregroundColor(.blue) ) } } .padding(.horizontal) } } }
2
0
212
Jul ’25
Beginner Question - Local SPM Folder Structure
Hi there, I am working on an iOS mobile app, with a MVVM architecture and created an SPM folders for my DesignSystem, CoreKit, UnityBridge, and VoicePipeline. I added the packages locally, and dragged them into the project. Is working this way recommended? Or not? Should all the SPM folders I listed above be used this way, or should only some? New to this, unsure what is best. I do plan on sharing my code with other devs to work on. I thought this made sense, but if i did it the other way I was unsure how I would share the packages what is a best practice. Thanks so much!
1
0
76
Jul ’25
The new framework AlarmKit is useless
what else can you do with it except for getting the alarm run off? and the alarm even gets dismissed when the user presses any buttons on device even volume buttons. I hope it's better by the time when iOS26 is officially released but I can't prepare for the new iOS update with this useless new framework. does anybody know what new features in this framework are coming up?
0
0
167
Jul ’25
SwiftUI vs Flutter for Embedding Unity in an iOS App?
I need help. Looking for devs who’ve integrated Unity into a native iOS app (Swift/SwiftUI) SwiftUI vs Flutter for Embedding Unity in an iOS App? I’m planning an iOS-first app where users interact with a real-time 3D custom avatar with 52 blendshapes powered by Unity, using SALSA LipSync + Emoter for facial animation. The avatar will respond to voice using Whisper → GPT-4 → ElevenLabs. My plan is to embed Unity only for the avatar screen, and build the rest of the app (chat, voice input, onboarding, etc.) natively? Here’s the decision I’m stuck on: Should I stick with SwiftUI, since it gives full access to iOS-native features like ARKit, audio routing, and StoreKit? I only plan to develop for iOS. Has anyone here integrated Unity with Flutter for mobile app successfully? Any pitfalls or major limitations I should know about before going that route? I haven’t started development yet — just want to make sure I choose the right foundation for performance, flexibility, and long-term growth. Any experience would be hugely appreciated!
1
0
188
Jul ’25
Compiling Swift Package with Dependency on Build Tool Plugin Fails in Xcode 26
Hi, in our Xcode project we have a Tooling package, which defines build tool plugins for generating compile time safe constants for our localization strings as well as assets using swiftgen. This is working very well in Xcode 16, but fails in Xcode 26 beta 1 and beta 2 as well. The failure is specifically: unsupported configuration: the aggregate target 'Localization' has package dependencies, but targets that build for different platforms depend on it. I've reduced this to a minimal sample project, which you can find here.. To reproduce: Open the Repro workspace, that is attached in Xcode. Try to build TestyPackage. You'll see the error. I've filed this bug during WWDC week, but no feedback yet and no solution in Xcode 26 beta 2. Here's the feedback number, in case you have this too and want to file a duplicate: FB17934050. Does anyone else have this issue and perhaps a solution?
2
3
149
Jul ’25
What is going on with transformable
Hi, I keep trying to use transformable to store an array of strings with SwiftData, and I can see that it is activating the transformer, but it keeps saying that I am still using NSArray instead of NSData. *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "category"; desired type = NSData; given type = Swift.__SwiftDeferredNSArray; value = ( yo, gurt ).' terminating due to uncaught exception of type NSException CoreSimulator 1010.10 - Device: iPhone 16 18.0 (6879535B-3174-4025-AD37-ED06E60291AD) - Runtime: iOS 18.0 (22A3351) - DeviceType: iPhone 16 Message from debugger: killed @Model class MyModel: Identifiable, Equatable { @Attribute(.transformable(by: StringArrayTransformer.self)) var category: [String]? @Attribute(.transformable(by: StringArrayTransformer.self)) var amenities: [String]? var image: String? var parentChunck: MyModelDataChunk_V1? init(category: [String]?, amenities: [String]?) { self.category = category self.amenities = amenities } } class StringArrayTransformer: ValueTransformer { override func transformedValue(_ value: Any?) -> Any? { print(value) guard let array = value as? [String] else { return nil } let data = try? JSONSerialization.data(withJSONObject: array, options: []) print(data) return data } override func reverseTransformedValue(_ value: Any?) -> Any? { guard let data = value as? Data else { return nil } let string = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String] print(string) return string } override class func transformedValueClass() -> AnyClass { return NSData.self } override class func allowsReverseTransformation() -> Bool { return true } static func register() { print("regitsering") ValueTransformer.setValueTransformer(StringArrayTransformer(), forName: .stringArrayTransformerName) } } extension NSValueTransformerName { static let stringArrayTransformerName = NSValueTransformerName("StringArrayTransformer") }
1
0
108
Jul ’25
Projecting a Cube with a Number in ARKit
I'm a novice in RealityKit and ARKit. I'm using ARKit in SwiftUI to show a cube with a number as shown below. import SwiftUI import RealityKit import ARKit struct ContentView : View { var body: some View { return ARViewContainer() } } #Preview { ContentView() } struct ARViewContainer: UIViewRepresentable { typealias UIViewType = ARView func makeUIView(context: UIViewRepresentableContext<ARViewContainer>) -> ARView { let arView = ARView(frame: .zero, cameraMode: .ar, automaticallyConfigureSession: true) arView.enableTapGesture() return arView } func updateUIView(_ uiView: ARView, context: UIViewRepresentableContext<ARViewContainer>) { } } extension ARView { func enableTapGesture() { let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:))) self.addGestureRecognizer(tapGestureRecognizer) } @objc func handleTap(recognizer: UITapGestureRecognizer) { let tapLocation = recognizer.location(in: self) // print("Tap location: \(tapLocation)") guard let rayResult = self.ray(through: tapLocation) else { return } let results = self.raycast(from: tapLocation, allowing: .estimatedPlane, alignment: .any) if let firstResult = results.first { let position = simd_make_float3(firstResult.worldTransform.columns.3) placeObject(at: position) } } func placeObject(at position: SIMD3<Float>) { let mesh = MeshResource.generateBox(size: 0.3) let material = SimpleMaterial(color: UIColor.systemRed, roughness: 0.3, isMetallic: true) let modelEntity = ModelEntity(mesh: mesh, materials: [material]) var unlitMaterial = UnlitMaterial() if let textureResource = generateTextResource(text: "1", textColor: UIColor.white) { unlitMaterial.color = .init(tint: .white, texture: .init(textureResource)) modelEntity.model?.materials = [unlitMaterial] let id = UUID().uuidString modelEntity.name = id modelEntity.transform.scale = [0.3, 0.1, 0.3] modelEntity.generateCollisionShapes(recursive: true) let anchorEntity = AnchorEntity(world: position) anchorEntity.addChild(modelEntity) self.scene.addAnchor(anchorEntity) } } func generateTextResource(text: String, textColor: UIColor) -> TextureResource? { if let image = text.image(withAttributes: [NSAttributedString.Key.foregroundColor: textColor], size: CGSize(width: 18, height: 18)), let cgImage = image.cgImage { let textureResource = try? TextureResource(image: cgImage, options: TextureResource.CreateOptions.init(semantic: nil)) return textureResource } return nil } } I tap the floor and get a cube with '1' as shown below. The background color of the cube is black, I guess. Where does this color come from and how can I change it into, say, red? Thanks.
4
0
113
Jul ’25
Avoiding Plugin Execution in a Linked Swift Package During Top-Level Package Builds
I am working on an iOS project using Xcode 16.0 that leverages multiple Swift packages. Among these, I have a Shared Package that contains reusable code and is linked to several top-level feature packages (e.g., VideoPlayer, VideoEditor, etc.). The Shared Package includes a Swift Package Manager plugin for linting code standards, which is designed to execute during its own build process. However, when building a top-level package (e.g., VideoPlayer), the Shared Package is also built as part of the dependency graph. During this process, the linting plugin in the Shared Package is executed unnecessarily, even though the intent is to only build the Shared Package's code. This behavior results in a significant increase in build times for the top-level packages, as the linting plugin is executed every time the Shared Package is built indirectly. Key Details: Xcode Version: 16.0 Swift Package Manager: Used for dependency management. Issue: The linting plugin in the Shared Package executes during the build of top-level packages, increasing build times. Expected Behaviour: The plugin should only execute when the Shared Package is built directly, not when it is built as a dependency of a top-level package. I would like to know if there is a way to configure the Shared Package or the Swift Package Manager to prevent the plugin from executing when the Shared Package is built as a dependency of a top-level package, while still allowing the plugin to run when the Shared Package is built directly. Any guidance, configuration tips, or best practices to address this issue would be greatly appreciated.
0
0
63
Jul ’25
SPM Package resources bundle id format has changed in Xcode 16
I have a project that uses local SPM packages for modularization. In one of my local SPM packages I have a .storyboard file that gets packaged as a resource in the SPM package and consumed inside the parent. In Xcode 15.4, the resource bundle for my local SPM Package has the bundle id PackageName-TargetName-resources. I use this inside a parent storyboard to reference the storyboard from the SPM package. In Xcode 16, however, the resource bundle for my SPM Package gets assigned the bundle id packagename.TargetName.resources. This, of courses, introduces a crash in builds of my app done with Xcode 16 due to the incorrect bundle id. There is no documentation of this change that I could find by Apple or by the SPM team. Apple Team: There is a Feedback Report FB14803020 with the build files attached from Xcode 15.4 and Xcode 16. I cannot attach those here due to the public nature of this forum
3
1
994
Jun ’25
HotKey support for sandboxed apps
App design: macos, Xcode 16.4, Sequioa 15.5, it is sandboxed Uses: Pods->HotKey for a global hotkey which xcode says "binary compatibility can't be guaranteed" This app is on the Apple Store and supposedly apps on the Apple Store can't use global hotkeys. Someone internally, installed it from the store and the global hotkey works just fine. I'm concerned for two potential problems; I need to find a hotkey library or code that is known to work with a sandbox'd Apple Store app. Why is it working now when everything I have read says it shouldn't.
0
0
116
Jun ’25