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

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
1
331
Dec ’24
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.") } }
2
1
502
Jan ’25
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
283
Dec ’24
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
331
Dec ’24
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
478
Dec ’24
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.
1
0
986
Dec ’24
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
232
Dec ’24
Unstable `archive` for `Debug` configuration (ld: file cannot be open()ed, errno=2)
We have a relatively big iOS-only project with around 80 build targets from swift packages (local features and external project dependencies) and Xcode 15.4 (originally, migrated to 16.0). Project compiles and runs great, but xcodebuild archive will fail 4 out of 5 tries with this: ld: file cannot be open()ed, errno=2 path=/opt/builds/fLLyxmhG/0/myapp/Build/Intermediates.noindex/ArchiveIntermediates/myapp (Development Flow)/BuildProductsPath/Debug-iphonesimulator/Account.o in '/opt/builds/fLLyxmhG/0/myapp/Build/Intermediates.noindex/ArchiveIntermediates/myapp (Development Flow)/BuildProductsPath/Debug-iphonesimulator/Account.o' Where Account.o is an end product of one of our feature packages linking to an .app itself. This error is not tied to this concrete package/product (which should be compiling almost last relative to build graph) and could appear mid-build in between our service layer packages. It seems (and is approved by Xcode timeline for .app archive log) that module dependency is compiled later than module itself and linker just cant find its dependency object files. The scheme is: Module A (dependency itself) Module B (needs module A) And with build order expected (???) to be A (first) -> B we're getting the B -> A. Error appears only when archiving for Debug configuration, archiving the same end-target with Release configuration results in stable passes 10 out of 10 tries. Setting identical parameters in Build Settings tab for both configurations of a target is not giving any effect. Our current fix is choosing Manual order in scheme Build order setting. Everything works as expected, but i guess it's not optimal 🀧 Sadly can't provide test project, but anything else β€” welcome.
0
1
398
Dec ’24
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
324
May ’25
Formal Complaint for Double Charge and Lack of Adequate Assistance
I am writing to express my deep dissatisfaction with a recent experience involving your services. I have discovered that I have been charged twice for the same product or service, which I find unacceptable. Additionally, I have not received the necessary support to resolve this issue, and the product or service in question does not function as it should. The treatment I have received has been neglectful and far below the standards I expect from a company that prides itself on providing quality service. This situation has not only shaken my confidence in your services but has also caused significant frustration as a customer. I demand an immediate resolution to this issue, including a refund for the duplicate charge and assurance that the purchased product or service will work as promised. If I do not receive a satisfactory response, I will be forced to take further action to protect my rights as a consumer. I look forward to your prompt response to resolve this matter.
1
0
271
Dec ’24
Import sqlite database to SwiftData
Hello, I recently switched my app from flutter which was using sqlite3 database. I would like to migrate my existing users to SwiftData. The issue is I do not know where to start in finding the database for the current users, reading the data and inserting into the SwiftData schema. I tried searching but not clear on how to proceed. Any help pointing in the right direction would be great. Thanks.
1
0
399
Nov ’24
How to do content transition when one image is a system symbol and the other is in assets catalouge?
I have a save button: Button(action: { saveTapped() }) { Label("Save", systemImage: wasSaved ? "checkmark" : "square.and.arrow.down") } .contentTransition(.symbolEffect(.replace)) .disabled(wasSaved) Now, I created a new custom icon and added it into the assets catalogue: "custom.square.and.arrow.down.badge.checkmark" for when the wasSaved state is true. The issue I am facing is that to use it I need to use the method of Label with image:, while to use the non custom symbol, I need to use systemImage:. So how is it possible to transition between the two?
1
0
472
Dec ’24
Does 'swift build' execute Test Code on macOS even for iOS Only Apps?
Hi, I have a library for my iOS Apps. It uses among other things the Combine framework, Core Location and OSLog. I manage the library using the Swift Package Manager (SPM) and usually build via XCode, which works fine. However for CI I would like to build everything from the terminal. So I do call 'swift build' on the terminal. This produces errors such as: 'PassthroughSubject' is only available in macOS 10.15 or newer 'os_log(:dso:log::_:)' is only available in macOS 10.14 or newer 'eraseToAnyPublisher()' is only available in macOS 10.15 or newer 'authorizedWhenInUse' is unavailable in macOS 'AnyPublisher' is only available in macOS 10.15 or newer 'showsBackgroundLocationIndicator' is unavailable in macOS ... These are all from the used frameworks. However, I do not care on which version of macOS, for example, PassthroughSubject is only available at, since the library is iOS only. Too make sure of that I added "platforms: [.iOS(.v14)]" to my Package.swift and thought this would be sufficient, so the project does not get build for macOS. Can anyone please tell me or give me a hint on what I am getting wrong here?
0
0
243
Nov ’24
Issue with using Swift package with xcframework binaryTarget
Hi! I'm trying to create a target application that depends on multiple targets that all use the same Swift package that has xcframework binaryTarget. Each component can be successfully assembled individually, but when I try to create a core application that depends on these components, I get an error message on Prepare build stage: Multiple commands produce '/Users/<USER>/Library/Developer/Xcode/DerivedData/<PROJECT_ID>/Build/Products/Debug/Frameworks/<FW_NAME>.framework/Versions/A' Target '<COMPONENT1>' has copy command from '/Users/<USER>/Library/Developer/Xcode/DerivedData/<PROJECT_ID>/SourcePackages/artifacts/.../<FW_NAME>/<FW_NAME>.xcframework/macos-arm64_x86_64/<FW_NAME>.framework' to '/Users/<USER>/Library/Developer/Xcode/DerivedData/<PROJECT_ID>/Build/Products/Debug/Frameworks/<FW_NAME>.framework' Target '<COMPONENT2>' has copy command from '/Users/<USER>/Library/Developer/Xcode/DerivedData/<PROJECT_ID>/SourcePackages/artifacts/.../<FW_NAME>/<FW_NAME>.xcframework/macos-arm64_x86_64/<FW_NAME>.framework' to '/Users/<USER>/Library/Developer/Xcode/DerivedData/<PROJECT_ID>/Build/Products/Debug/Frameworks/<FW_NAME>.framework' – where <FW_NAME> is a name of the xcframework which is the binaryTarget in the Swift package. Could someone please explain to me if it is even possible to use xcframeworks packaged in Swift packages in such cases, and if so, how to do it correctly?
0
0
343
Nov ’24
How swift string is internally managing memory ?
When i create a intance of swift String : Let str = String ("Hello") As swift String are immutable, and when we mutate the value of these like: str = "Hello world ......." // 200 characters Swift should internally allocate new memory and copy the content to that buffer for update . But when i checked the addresses of original and modified str, both are same? Can you help me understand how this allocation and mutation working internally in swift String?
1
0
500
Nov ’24
How the input of UITextField is stored ?
When user enters in a textfield, is the input of textfield gets stored in a String ? If yes, then String in swift being immutable, as user keeps on typing does new memory for storing that text gets allocated with each key stroke ? And when we read users input by using delegate method textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) from textfield.text, we get users input in a String. Is it same storage as used by textfield for storing the user input on key stroke or is it some other storage with copy of the user's input in it? Or is UItextfield using a diffrent data structure (buffer) for storing the user input and when we do textfield.text, it gives a copy of data stored in original buffer?
1
0
582
Nov ’24