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
Sort by:

Post

Replies

Boosts

Views

Activity

Can you add pictures with the camera using the new photos picker instead of the old UI View Controller?
I'm a new app developer and am trying to add a button that adds pictures from the photo library AND camera. I added the first function (adding pictures from the photo library) using the new-ish photoPicker, but I can't find a way to do the same thing for the camera. Should I just tough it out and use the UI View Controller struct that I've seen in all of the YouTube tutorials I've come across? I also want the user to be able to crop the picture in the app after they take a picture. Thanks in advance
1
0
136
2d
scrollTargetLayout + @FetchRequest causes items to constantly re-initialize
On a ScrollView+LazyVStack, the addition of .scrollTargetLayout causes many list items to be initialized, instead of the ordinary economical behavior of LazyVStack, where only the necessary items and views are initialized. Even worse, as the stack is scrolled down, all list items are reinitialized for every small scroll. Without, .scrollTargetLayout, everything works fine. I've tried every variation of locating modifiers, and different ways of identifying the list items, with no success. Any ideas? Thanks. @FetchRequest( sortDescriptors: [NSSortDescriptor(keyPath: \Post.created, ascending: true)], animation: .default) private var posts: FetchedResults<Post> var body: some View { ZStack{ ScrollView{ LazyVStack(spacing:0) { ForEach(posts, id: \.self) { post in PostView(post: post) } .onDelete(perform: deletePosts) }.scrollTargetLayout() // <---- causes multiple Posts re-instantiations for any small scroll, very slow } .scrollPosition(id: $scrolledID) .scrollTargetBehavior(.paging)
1
0
73
3d
GeometryReader problem
I'm adding Admob ads to my app, and Admob needs to know the width of the view, so I'm using GeometryReader for that. To prevent GeometryReader from grabbing screen space, I've wrapped the main view in GeometryReader { }. I then use geometry.size.width in my call to the adView. This all works fine. I have two main screens where I show ads, and they both work, until I rotate the device. Then the app crashes! If I comment out the GeometryReader code and pass a fixed value to the ad view, I can rotate the device with no fear of a crash. My question is: Do I have to accept that GeometryReader will crash the app when it's rotated, or is there another, stable way to get view dimensions?
3
0
91
2d
Reusing string catalog translations in swift packages
Setup I have 2 swift packages and I try to use stirng catalog to manage your localizations I would like to use some specific keys in these packages and some common ones (e.g. "ok_button_tittle") Problem statement I really don't like the idea of creating separate (but the same) translations in these packages I have tried using something like String( localized: "ok_button_title", table: "Localizable", bundle: .main, comment: "Ok button title" ) This does use translations from the main bundle, however this does not automatically create the keys in string catalog Question Is there any possibility to reuse the translations from the main bundle? Maybe there is a hack to make the keys appear automatically in the correct bundle? Or is it a bug?
0
0
59
3d
Package platforms not working
I am writing a package in Swift using Xcode 16.1 (swift-tools-version: 6.0) and am trying to use features that became available in later versions of macOS and iOS. The following line naturally causes a compiler error when compiling against 'My Mac': let match = "test-string".firstMatch(of: /-(.+)/)! 'firstMatch(of:)' is only available in macOS 13.0 or newer I can of course fix this by using @available(macOS 13.0, *), but there are dozens of methods and I would prefer to use the platforms property in the Package file like this: platforms: [ .macOS(.v10_13), .iOS(.v16) ], However for reason that are not clear, this does not work and the compiler errors remain. I have tried cleaning, removing derived data etc. What I am doing wrong?
2
0
98
3d
Slow bundle copy build phase from dependency
We have a dependency, Apollo iOS, that is managed by SwiftPM in an internal module Swift Package. That internal Swift Package is then linked and included in our iOS target. The iOS target has an associated WidgetKit extension app. When archiving the app, we're seeing extremely long "Copy Apollo_Apollo.bundle" build steps, on the magnitude of 15 minutes. This is only happening when copying the bundle for the Widget extension app. Builds are done with Xcode 15.2, but we've tried on 15.4 and 16.2, seeing a few minutes shaved off. How can we begin to debug this issue?
0
0
47
4d
xcodebuild: "error: …/build/Release/Defaults_Defaults.bundle: No such file or directory"
This is probably a beginner's mistake, but I can't find anything about this error anywhere, and it's completely reproducible, even on GitHub Runners and with a fresh Xcode project. The error doesn't seem to be caused by the Swift package used, Defaults, but by xcodebuild. macOS Sequoia 15.2 (24C101) Xcode Version 16.2 (16C5032a) Defaults Version 9.0.0 When following Defaults' installation instructions, building and archiving from Xcode still works fine, but building with xcodebuild always fails with this error: Copy /Users/user/DefaultsTest/build/Release/DefaultsTest.app/Contents/Resources/Defaults_Defaults.bundle /Users/user/DefaultsTest/build/Release/Defaults_Defaults.bundle (in target 'DefaultsTest' from project 'DefaultsTest') cd /Users/user/DefaultsTest builtin-copy -exclude .DS_Store -exclude CVS -exclude .svn -exclude .git -exclude .hg -resolve-src-symlinks /Users/user/DefaultsTest/build/Release/Defaults_Defaults.bundle /Users/user/DefaultsTest/build/Release/DefaultsTest.app/Contents/Resources error: /Users/user/DefaultsTest/build/Release/Defaults_Defaults.bundle: No such file or directory (in target 'DefaultsTest' from project 'DefaultsTest') I made a fresh, reproducible Xcode project here: https://github.com/F1248/DefaultsTest And a failing GitHub Action here: https://github.com/F1248/DefaultsTest/actions/runs/12303972248/job/34340347771 Any help would be greatly appreciated.
2
0
118
5d
Updating Swift Packages via command line (Xcode 16)
We have a tool in our CI which periodically updates our iOS project's Swift Package Manager dependencies. The script that does a few things, but generally speaking it first removes the existing package.resolved at ./ProjectName.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved and then runs: xcodebuild -resolvePackageDependencies -disablePackageRepositoryCache This regenerated the package.resolved file to reflect the latest, updated versions of the dependencies. It is the equivalent of doing Xcode > File > Packages> Update to Latest Package Versions. This has been working perfectly for a long time, but has stopped working since we moved from Xcode 15.4 to Xcode 16. I have also tested this with Xcode 16.1 and 16.2 - with no luck. I have tried running this command locally, and can confirm it is not an issue with the environment of our CI. I have also tried swift package update. Both of these commands appear to work - no errors are thrown, and the logs say "resolved source packages". However, they are not updating the packages. They are making no changes to the package.resolved file. However, using Xcode > File > Packages> Update to Latest Package Versions in Xcode 16 works as expected - the packages are updated and the .resolved file is updated. Is there now a different way to update Swift packages via the command line, or is this likely an Xcode 16 bug? Update: This feels broken, so I have submitted a Feedback Report (FB16108036) but perhaps someone can suggest a workaround for the time being!
0
0
122
5d
Code coverage problem with symbolic linked source files
Let's say I have a local package Foo, Bar and Baz. Foo has Bar and Baz as dependency and has test target,FooTests. Below is the Package.swift manifest that describes package Foo. import PackageDescription let packages: [Package.Dependency] = [ .package(path: "../Bar"), .package(path: "../Baz"), ] let products: [Target.Dependency] = [ .product(name: "Bar", package: "Bar"), .product(name: "Baz", package: "Baz"), ] let package = Package( name: "Foo", platforms: [ .iOS(.v16), ], products: [ .library( name: "Foo", targets: ["Foo"] ), ], dependencies: packages, targets: [ .target( name: "Foo", dependencies: products, path: "Sources" ), .testTarget( name: "FooTests", dependencies: [.target(name: "Foo")], path: "Tests", swiftSettings: swiftSettings ), ] ) Bar and Baz is also local packages. Due to the limitations of the project, Baz has sources with symbolic links instead of exact directories, and these sources are what FooTests will test. If I run FooTests, test succeed with proper logs indicating that all test methods are run correctly, but test coverage says that Baz's coverage is 0% and there is no executable lines unlike the Bar which is not what be tested. Is there any way to fix this problem?
0
0
63
5d
App Rejected: Non-Public Symbols _lzma_code and _lzma_end in Payload/Hogs.app/Hogs
Hello, I have integrated LZMA2 compression into my iOS app, Hogs, and successfully implemented compression. However, when attempting to upload the app for TestFlight, I encountered an error: "The app references non-public symbols in Payload/Hogs.app/Hogs: _lzma_code, _lzma_end." These functions are part of the LZMA compression library (specifically LZMA2). Here's a detailed description of the issue: What I Have Done: LZMA2 Integration: I integrated LZMA2 compression into the app and created a wrapper around the LZMA functions (_lzma_code, _lzma_end) to prevent direct references. App Build Configuration: I ensured the LZMA2 library is linked correctly with the -lzma flag in the linker settings. I wrapped the LZMA functions in custom functions (my_lzma_code, my_lzma_end) in an attempt to avoid using the non-public symbols directly. Error Message: During the app submission process, I received the following error: "The app references non-public symbols in Payload/Hogs.app/Hogs: _lzma_code, _lzma_end." Steps Taken to Resolve: Checked if any LZMA functions were exposed incorrectly. Ensured that all non-public symbols were properly encapsulated in a wrapper. Verified linker settings to ensure the proper inclusion of the LZMA2 library. Request: Could anyone provide suggestions or best practices to resolve this issue and avoid references to non-public symbols? Should I use a different method for linking LZMA2 or encapsulating these symbols? Thank You: I appreciate your help in resolving this issue so I can move forward with submitting the app for TestFlight.
1
0
81
5d
Adding logging to a SwiftUI View's body var
Pretty sure this is a no-no, but asking just in case there's an easy way to make this work struct DocumentContentView: View { private static let logger = Logger( subsystem: "mySubsystem", category: String(describing: Self.self) ) var body: some View { VStack { Text("Hello") logger.trace("hello") } } } This code generates the following compile error at the logger.trace line buildExpression is unavailable: this expression does not conform to View I suspect every line of the body var (or any @ViewBuilder - designated code?) needs to 'return' a View. Is this correct? or more importantly any work arounds other than putting some/all of the view contents in a. func()?
2
0
134
5d
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 !
4
1
149
1w
Text input going to terminal instead of TextEditor/TextView
I'm making an app using SwiftUI and trying to use the TextEditor view. However when I run it, and I try entering text into the TextEditor, the characters don't appear, they do however appear in the terminal that i used to run the app. The same problem exists with the TextField view. I usually run it using swift run but have also tried swift build and running the produced executable as well as using release mode. Minimal example: import SwiftUI @main struct Example: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { @State var text: String = "" var body: some View { TextEditor(text: $text) } }
1
0
111
1w
Feature Request: Authorize api.github.com
Issue Description I'm have Local Swift Package which contains binary target to private github releases url is formed like below: https://api.github.com/repo/{owner}/{repo}/releases/assets/{asset_id}.zip I register the private repo to the xcodecloud, but still xcodecloud does not recognize "api.github.com" domain. So build keeps fails at downloading binary artifact. https://github.com/{owner}/{repo}/releases/download/{tag}/Myframework.xcframework.zip is not a valid choice since this kind of url, is not supported for private repository. Proposed Solution Please add authorization to the "api.github.com" like normal "github.com".
1
0
115
1w
DeviceActivityMonitor - Callbacks not trigger
Bellow I created Manager to be easier for me to handle app limits, but for some reason It never reached callbacks function, I have permission for screen time, I added the capabilities for it also, I'm sure, I send correctly the appTokens, categoriesTokens ... and the time limit and it also reach ✅ Monitoring started for..., I don't know what to do anymore: import SwiftUI import DeviceActivity import FamilyControls import ManagedSettings @MainActor class AppUsageManager: DeviceActivityMonitor, ObservableObject { static let shared = AppUsageManager() private let deviceActivityCenter = DeviceActivityCenter() private var monitoringSelections: [DeviceActivityName: (selection: FamilyActivitySelection, timeLimit: DateComponents)] = [:] private var resetTimer: Timer? private override init() { super.init() print("🟢 AppUsageManager initialized.") } // MARK: - Public Methods /// Configures monitoring for a selection with a specific event name and time limit. func configureMonitoring( for selection: FamilyActivitySelection, timeLimitInMinutes: Int, activityName: String, eventName: String ) { let activityName = DeviceActivityName(activityName) let eventName = DeviceActivityEvent.Name(eventName) monitoringSelections[activityName] = (selection, DateComponents(minute: timeLimitInMinutes)) setupMonitoring(for: activityName, with: eventName) } /// Stops monitoring for a specific event. func stopMonitoring(for activityName: String) { let activityName = DeviceActivityName(activityName) Task { print("🛑 Stopping monitoring for \(activityName.rawValue).") deviceActivityCenter.stopMonitoring([activityName]) monitoringSelections.removeValue(forKey: activityName) } } /// Stops all monitoring. func stopAllMonitoring() { print("🛑 Stopping monitoring") deviceActivityCenter.stopMonitoring() } // MARK: - Private Methods /// Sets up monitoring for a specific event. private func setupMonitoring( for activityName: DeviceActivityName, with eventName: DeviceActivityEvent.Name ) { stopAllMonitoring() guard let (selection, timeLimit) = monitoringSelections[activityName] else { print("⚠️ No selection configured for \(activityName.rawValue).") return } print("🛠 Setting up monitoring for \(activityName.rawValue).") print("📋 Monitoring Details:") print("- Time Limit: \(timeLimit.minute ?? 0) minutes.") let warningThreshold = DateComponents(minute: 3) let timeZone = TimeZone.current let schedule = DeviceActivitySchedule( intervalStart: DateComponents(timeZone: timeZone, hour: 0, minute: 0, second: 0), intervalEnd: DateComponents(timeZone: timeZone, hour: 23, minute: 59, second: 59), repeats: true, warningTime: warningThreshold ) let events: [DeviceActivityEvent.Name: DeviceActivityEvent] = [ eventName: DeviceActivityEvent( applications: selection.applicationTokens, categories: selection.categoryTokens, webDomains: selection.webDomainTokens, threshold: timeLimit ) ] do { try deviceActivityCenter.startMonitoring( activityName, during: schedule, events: events ) print("✅ Monitoring started for \(activityName.rawValue) with time limit \(timeLimit.minute ?? 0) minutes.") } catch { print("❌ Failed to start monitoring \(activityName.rawValue): \(error.localizedDescription)") } } // MARK: - DeviceActivityMonitor Overrides override func intervalDidStart(for activity: DeviceActivityName) { print("🟢 Interval for \(activity.rawValue) started.") } override func intervalWillStartWarning(for activity: DeviceActivityName) { print("⚠️ Warning: \(activity.rawValue) is about to start.") } /// Handles warnings for approaching the time limit. override func eventWillReachThresholdWarning( _ event: DeviceActivityEvent.Name, activity: DeviceActivityName ) { super.eventWillReachThresholdWarning(event, activity: activity) print("⚠️ Warning: \(activity.rawValue) is about to reach its time limit.") print("⚠️ Event: \(event.rawValue)") } /// Handles when the time limit is reached. override func eventDidReachThreshold( _ event: DeviceActivityEvent.Name, activity: DeviceActivityName ) { super.eventDidReachThreshold(event, activity: activity) print("🟢 Limit reached.") Task { @MainActor in print("🕒 \(activity.rawValue) has reached its time limit.") print("🕒 Event: \(event.rawValue)") guard let (selection, _) = monitoringSelections[activity] else { print("⚠️ No selection configured for \(activity.rawValue).") return } blockApps(for: selection) } } // MARK: - Blocking Logic /// Blocks the selected apps/categories. private func blockApps(for selection: FamilyActivitySelection) { print("🔒 Blocking apps/categories for selection.") print("- Applications: \(selection.applicationTokens)") print("- Categories: \(selection.categoryTokens)") let store = ManagedSettingsStore() store.shield.applications = selection.applicationTokens store.shield.applicationCategories = .specific(selection.categoryTokens) print("🔒 Apps/categories blocked successfully.") } }
1
1
134
1w
Moving files to local package not possible in Xcode 16?
Hi! Trying to move some code into a local package - with Xcode 16 I am unable to move my code to the new package as drag and drop will always result in a copy. This contradicts the demo in the original intro session at WWDC19, and also the current documentation.. Of course I can delete the original files but this feels somewhat wrong... Am I missing something? Did the behaviour of moving files in the Project navigator change in the recent Xcode releases?
0
0
99
1w
App archive wrong runner
I am facing a serious and urgent issue. I am trying to build my app for an update on the Store, but in Xcode, instead of archiving the expected Runner application, the archive is successfully created, yet it is not associated with the correct Runner. As a result, I am unable to upload and distribute the app to the Store after the build. I have been stuck on this issue for two days, trying every possible solution, but I cannot identify what is wrong or causing the problem. Could someone please assist or guide me on how to resolve this? I would greatly appreciate any help. Thank you in advance. Please check the screenshots:
1
0
137
1w
Assets.xcassets vs. Media.xcassets
In Xcode 16, when I use File > New > Project to create a new iOS app project, Xcode automatically creates an asset catalog file called Assets.xcassets in the project. However, if I later use File > New > File from Template, for example to add an asset catalog to an embedded Swift package within a project, Xcode suggests the default filename Media.xcassets for the file, instead of Assets.xcassets. Why is the default name for this file different in each context? Thank you for explaining this troubling consistency issue which causes me to lie awake at night.
1
0
101
1w
Modularizing an Xcode 16 project
My preferred way of setting up an app project no longer works in Xcode 16. I like to have my apps massively modularized - a separate SPM module for every significant feature. I use a project grouped together with a package that contains all the feature modules. The project's app target imports a consolidated AppFeature from the package that is all the logic of the app. In Xcode 15 and before, I had a process for creating this kind of setup (described below -- unfortunately the forums don't support collapsible sections). Where I used to be able to drag a directory from Finder into the Xcode files navigator (step 6 in my process), it now rejects the drag. What I'm looking for is a way to have a single window open that has my Swift package and below that a separate folder for each executable target. Creating new modules in the package automatically creates new schemes in Xcode. Executable targets in the project can reference any module in the package. Source control treats the entire thing as one repository. I've tried all the approaches I can think of to accomplish the same goal, but no luck. The projects I've already built work fine in Xcode 16 -- I just can't make a new one. Unfortunately I can't revert to Xcode 15 for this purpose since it apparently doesn't run on my work machine with macOS 15. Here's my process that worked great till now: In Terminal, create the project folder Foo: $ mkdir Foo $ cd Foo Create the package: $ swift package init Creating library package: Foo Creating Package.swift ... Create a directory for the project: $ mkdir App In Xcode, create a new app project called Foo and put it in the App folder Open the Foo project Drag the top level Foo directory from Finder into the Xcode project and drop it immediately under the project name Close the Xcode project Create a file called Package.swift and place it in the App folder. Edit it to have an empty package content. This ensures Xcode won’t display that folder in the source navigator under the package header. import PackageDescription let package = Package( name: "", products: [], dependencies: [], targets: [] ) Open the Xcode project. You should have top-level project name* Foo*. Under that will be the package, also named Foo. Then there will be the app target, also named Foo. You can rename the app target folder Foo to something like iOS if you want to have other targets for other platforms like macOS.
0
0
162
1w
Xcode Doesn't recognises the git worktree version of the swift package
I'm building an iOS app using Xcode, and I frequently modify code within a package. To do this, I drag and drop a locally cloned version of the package into my project as a local package. However, when working across multiple branches of my app, I need different versions of the package as well. To achieve this, I use Git worktrees to create branch-specific copies of the package. Unfortunately, when I drag and drop these worktree copies into Xcode, the IDE doesn't seem to recognize them. Could you kindly guide me on resolving this?
0
0
94
1w