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

Calling Async Functions in SwiftUI
Hi, I'd like to call an Async function upon a state change or onAppear() but I'm not sure how to do so. Below is my code: .onAppear() { if !subscribed { await Subscriptions().checkSubscriptionStatus() } } class Subscriptions { var subscribed = UserDefaults.standard.bool(forKey: "subscribed") func checkSubscriptionStatus() async { if !subscribed { await loadProducts() } } func loadProducts() async { for await purchaseIntent in PurchaseIntent.intents { // Complete the purchase workflow. await purchaseProduct(purchaseIntent.product) } } func purchaseProduct(_ product: Product) async { // Complete the purchase workflow. do { try await product.purchase() } catch { // Add your error handling here. } // Add your remaining purchase workflow here. } }
0
0
68
2d
Custom Intent ParameterSummary based on Widget Kind/ID
I'm trying to create two widgets, widget A and B. Currently A and B are very similar so they share the same Intent and Intent Timeline Provider. I use the Intent Configuration interface to set a parameter, in this example lets say its the background tint. On one of the widgets, widget A, I want to also set another String enum parameter (for a timescale), but I don't want this option to be there for widget B as it's not relevant. I'm aware of some of the options for configuring the ParameterSummary, but none that let me pass in or inject the "kind" string (or widget ID) of the widget that's being modified. I'll try to provide some code for examples. My Widget Definition (targeting >= iOS 17) struct WidgetA: Widget { // I'd like to access this parameter within the intent let kind: String = "WidgetA" var body: some WidgetConfiguration { AppIntentConfiguration(kind: kind, intent: WidgetIntent.self, provider: IntentTimelineProvider()) { entry in WidgetView(data: entry) } .configurationDisplayName("Widget A") .description("A widget.") .supportedFamilies([.systemMedium, .systemLarge]) } } struct WidgetB: Widget { let kind: String = "WidgetB" var body: some WidgetConfiguration { AppIntentConfiguration(kind: kind, intent: WidgetIntent.self, provider: IntentTimelineProvider()) { entry in WidgetView(data: entry) } .configurationDisplayName("Widget B") .description("B widget.") .supportedFamilies([.systemMedium, .systemLarge]) } } struct IntentTimelineProvider: AppIntentTimelineProvider { typealias Entry = WidgetIntentTimelineEntry typealias Intent = WidgetIntent ........ } struct WidgetIntent: AppIntent, WidgetConfigurationIntent { // This intent allows configuration of the widget background // This intent also allows for the widget to display interactive buttons for changing the Trend Type static var title: LocalizedStringResource = "Widget Configuration" static var description = IntentDescription("Description.") static var isDiscoverable: Bool { return false} init() {} init(trend:String) { self.trend = trend } // Used for implementing interactive Widget func perform() async throws -> some IntentResult { print("WidgetIntent perform \(trend)") #if os(iOS) WidgetState.setState(type: trend) #endif return .result() } @Parameter(title: "Trend Type", default: "Trend") var trend:String // I only want to show this parameter for Widget A and not Widget B @Parameter(title: "Trend Timescale", default: .week) var timescale: TimescaleTypeAppEnum? @Parameter(title: "Background Tint", default: BackgroundTintTypeAppEnum.none) var backgroundTint: BackgroundTintTypeAppEnum? static var parameterSummary: some ParameterSummary { // Summary("Test Info") { // \.$timescale // \.$backgroundTint // } // An example of a configurable widget parameter summary, but not based of kind/ID string When(\.$backgroundTint, .equalTo, BackgroundTintTypeAppEnum.none) { Summary("Test Info") { \.$timescale \.$backgroundTint } } otherwise : { Summary("Test Info") { \.$backgroundTint } } } } enum TimescaleTypeAppEnum: String, AppEnum { case week case fortnight static var typeDisplayRepresentation = TypeDisplayRepresentation(name: "Trend Timescale") static var caseDisplayRepresentations: [Self: DisplayRepresentation] = [ .week: "Past Week", .fortnight: "Past Fortnight" ] } enum BackgroundTintTypeAppEnum: String, AppEnum { case blue case none static var typeDisplayRepresentation = TypeDisplayRepresentation(name: "Background Tint") static var caseDisplayRepresentations: [Self: DisplayRepresentation] = [ .none: "None (Default)", .blue: "Blue" ] } I know I could achieve what I'm after by having a separate Intent and separate IntentTimelineProvider for each widget. But this all seems unnessecary for just a simple optional parameter based on what widget its configuring.... unless I'm missing the point about Intents, Widgets or something! I've done a fair bit of other searching but can't find an answer to this overall scenario. Many thanks for any help.
1
0
86
2d
RealityView Not Refreshing With SwiftData
Hi, I am trying to update what entities are visible in my RealityView. After the SwiftData set is updated, I have to restart the app for it to appear in the RealityView. Also, the RealityView does not close when I move to a different tab. It keeps everything on and tracking, leaving the model in the same location I left it. import SwiftUI import RealityKit import MountainLake import SwiftData struct RealityLakeView: View { @Environment(\.modelContext) private var context @Query private var items: [Item] var body: some View { RealityView { content in print("View Loaded") let lakeScene = try? await Entity(named: "Lake", in: mountainLakeBundle) let anchor = AnchorEntity(.plane(.horizontal, classification: .any, minimumBounds: SIMD2<Float>(0.2, 0.2))) @MainActor func addEntity(name: String) { if let lakeEntity = lakeScene?.findEntity(named: name) { // Add the Cube_1 entity to the RealityView anchor.addChild(lakeEntity) } else { print(name + "entity not found in the Lake scene.") } } addEntity(name: "Island") for item in items { if(item.enabled) { addEntity(name: item.value) } } // Add the horizontal plane anchor to the scene content.add(anchor) content.camera = .spatialTracking } placeholder: { ProgressView() } .edgesIgnoringSafeArea(.all) } } #Preview { RealityLakeView() }
3
0
206
3d
Reproducible Builds on iOS
Dear Apple Developer Forum! I'm in need of help regarding an issue that has to do with binaries. I'm building an iOS App that needs a fingerprint of its binaries, exclusively based on the source code written. A "reproducible" build, meaning that when I compile it on my machine and run checksum on it, the output (hash) will be the same, as if another device clones the project, compiles and checksums the values. The App depends on swift packages which depends on Swift Packages, which I've managed to compile to .o files, convert to .a files (static frameworks) and create xcframeworks, which the App depends on. They work great, once compiled, their checksum value does not change when App is compiled (unless source code of them is changed of course), but the Apps executable (checksummed inside the IPA) changes every time it's compiled. I'm guessing that perhaps the Xcode compiler injects a timestamp or other unique identifier in the binaries? Is there any way to have "reproducible" builds on iOS (Swift Xcode)? All input is greatly appreciated, Thank you very much, Kind regards Johan.
4
0
160
1w
backgroundPreferenceValue does not work after distributed through App Connect
Hi, I'm new to software development and facing a problem that don't know how to solve. I have a piece of code using .backgroundPreferenceValue and .anchorPreference modifiers to monitor a button's position while dragging. It works perfectly on preview, simulator, and my own device if I download it through a cable connected to my computer. However, today I distributed it to TestFlight and found out it broke. I repeated the process serval times but the result is still the same. Has anybody run into the same type of problem before? Desperately need help. Many many thanks!
2
0
200
2w
How to Add .mlmodel File to Xcode App Playgrounds (.swiftpm) Project?
I’m working on an Xcode App Playground project (.swiftpm) and trying to add a .mlmodel file (e.g., Exercises.mlmodel) to it. However, when I add the .mlmodel file to my project, I encounter the following error: Exercises.mlmodel: No predominant language detected. Set COREML_CODEGEN_LANGUAGE to preferred language. The .mlmodel file works perfectly fine when used in a regular Xcode project (.xcodeproj), but this issue occurs as soon as I add the file in an App Playground project (.swiftpm). Steps I’ve Tried: Ensuring the .mlmodel file is correctly added to the project folder. Checking the generated Core ML Swift code in a .xcodeproj environment—works as expected. Searching for a way to explicitly set COREML_CODEGEN_LANGUAGE in a .swiftpm project, but it seems that Xcode does not provide this option. Any advice or solutions would be greatly appreciated! I have tried the solutions in these articles, however none of them worked: https://medium.com/@sofiadinizms/how-to-use-coreml-in-swift-playgrounds-8d5f001c5d15 https://developer.apple.com/forums/thread/743942?answerId=776359022#776359022
1
0
177
2w
Assistance Needed: App Submission Issue (ITMS-90426)
Hello, We submitted our app on TestFlight, but received an automated response with the following error: ITMS-90426: Invalid Swift Support - The SwiftSupport folder is missing. Rebuild your app using the current public (GM) version of Xcode and resubmit it. Our app is developed entirely in Objective-C, and we’re unsure why it’s looking for SwiftSupport. Despite attempting several potential solutions, the error persists. Could someone please assist us with understanding why this is happening and advise on how to proceed with the submission? Any guidance would be greatly appreciated. Thank you for your help.
1
0
197
3w
Build input file cannot be found
I have a project that imports SPM swift-navigation which in-turn imports SPM https://github.com/pointfreeco/swift-perception I have a test target it builds and runs with no issues in XCode however if I run with xcodebuild i get the below error (I have done basics removed derived data etc.) ❌ error: Build input file cannot be found: '/Users/chris/mtp-iOS-retail-iPhone/build/Build/Products/Debug/PerceptionMacros'. Did you forget to declare this file as an output of a script phase or custom build rule which produces it? (in target 'Perception' from project 'swift-perception')
0
0
171
3w
Using Core ML in a .swiftpm file
Hi everyone, I've been struggling for a few weeks to integrate my Core ML Image Classifier model into my .swiftpm project, and I’m hoping someone can help. Here’s what I’ve done so far: I converted my .mlmodel file to .mlmodelc manually via the terminal. In my Package.swift file, I tried both "copy" and "process" options for the resource. The issues I’m facing: When using "process", Xcode gives me the error: "multiple resources named 'coremldata.bin' in target 'AppModule'." When using "copy", the app runs, but the model doesn’t work, and the terminal shows: "A valid manifest does not exist at path: .../Manifest.json." I even tried creating a Manifest.json manually to test, but this led to more errors, such as: "File format version must be in the form of major.minor.patch." "Failed to look up root model." To check if the problem was specific to my model, I tested other Core ML models in the same setup, but none of them worked either. I feel stuck and unsure of how to resolve these issues. Any guidance or suggestions would be greatly appreciated. Thanks in advance! :)
2
1
467
2w
Unexpected Frame Resizing Behavior During Animation of safeAreaInset content.
Hey everyone! I’m encountering an issue while attempting to animate height changes of the content inside safeAreaInset(edge:alignment:spacing:content:). When animating a reduction in the frame height, the container view (in my case, Map) also animates unexpectedly. However, when animating an increase in the frame height, the animation works smoothly, and the Map view remains still. How can I address this odd resizing behavior of the container? Code: struct MapView: View { var body: some View { Map() .safeAreaInset(edge: .bottom) { MapDetailView() } } } struct MapDetailView: View { @State private var oldHeightOffset: CGFloat = 0 @State private var newHeightOffset: CGFloat = 0 @State private var containerHeight: CGFloat = 0 private var drag: some Gesture { DragGesture(coordinateSpace: .global) .onChanged { value in withAnimation(.interactiveSpring) { newHeightOffset = oldHeightOffset + value.translation.height } } .onEnded { value in switch newHeightOffset { case containerHeight * 0.625...containerHeight: withAnimation(.spring) { newHeightOffset = containerHeight * 0.75 } case containerHeight * 0.25..<containerHeight * 0.625: withAnimation(.spring) { newHeightOffset = containerHeight * 0.5 } case 0..<containerHeight * 0.25: withAnimation(.spring) { newHeightOffset = 0 } default: break } oldHeightOffset = newHeightOffset } } var body: some View { NavigationStack { Rectangle() .fill(.clear) .containerBackground(.ultraThinMaterial, for: .navigation) } .gesture(drag) .containerRelativeFrame(.vertical) { length, _ in length - newHeightOffset } .onGeometryChange(for: CGFloat.self) { geometryProxy in let frame = geometryProxy.frame(in: .local) return frame.height + newHeightOffset } action: { containerHeight in self.containerHeight = containerHeight } } } Reducing safe area inset's content height (drag down): Increasing safe area inset's content height (drag up):
2
0
224
2w
Xcode 构建失败:无法加载传输的 PIF,GUID 冲突错误
在Mac OS 15.2 使用 Xcode 16.2 构建项目时,我遇到了以下错误: Showing All Errors Only Prepare packages Prepare build Build service could not create build operation: unable to load transferred PIF: The workspace contains multiple references with the same GUID 'PACKAGE:1Y9CU7L2QFO7OX4UJBYP19ZPPL5MJNV3R::MAINGROUP' Activity Log Complete 2024/12/24, 15:26 0.2 seconds
0
0
174
Dec ’24
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
327
Dec ’24
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)
2
1
202
4w
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
210
Dec ’24
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?
1
0
186
3w