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

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
Invalid Swift Support - The SwiftSupport folder is missing
Hi When attempting to upload a React Native app (version 0.77) we encountered 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. If to check ipa folder we can see that content includes only 2 folders: Payload Symbols Could you please tell us why it does not include Swift Support folder? We tried to use XCode - 16.2 and 16.3 Thank you
3
0
218
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
92
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
57
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.2k
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
507
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
60
Apr ’25
I made a browser plugin to do something Apple should've done themselves.
This browser extension is a doc reading enhancer for the Apple Developer website. It supports i18n translation, hover link previews, and bilingual display. Currently, it supports four languages: ja-JP, ko-KR, zh-CN, and zh-TW. It works with Swift/SwiftUI/Foundation modules now, and it's expected to support Swift Test, Swift Charts, UIKit, Swift Playground, and XCode modules by the end of this month. For more info, check out: https://appledocs.dev. You can also visit https://appledocs.dev/progress to see translation progress and vote. Note: It's only works on Chrome、Edge(In review)、Firefox(In review) Screenshot:
1
0
100
Apr ’25
Above Xcode16 operation project, in the project use AVPictureInPictureController opportunities (PIP) function open system blackout
I found that when the development tool above Xcode16 ran my app, I opened the suspended inscription function, and then opened the system camera, the content in the suspended window would not be displayed, and the suspended window would have a black screen. However, this phenomenon does not appear on Xcode15.4 development tools, it is the same code, I do not know why
6
0
628
Apr ’25
Best Practices: Dependency management for local packages
I have a project which contains local packages. One of the packages has an explicit dependency on package A, but the main project also has the same dependency. Both of them are pinned to the exact version at all times. Should I manage "shared" dependencies at the project level for local packages? This seems counter intuitive at first, but this question is originating from me fighting with a "Build service could not create build operation: unable to load transferred PIF: The workspace contains multiple references with the same GUID" error in Xcode 16 (all versions). It happens when I switch branches. Closing and reopening Xcode does resolve the issue, but it's a real flow killer. The guide below doesn't mention dependency graph best practice. https://developer.apple.com/documentation/xcode/organizing-your-code-with-local-packages Thank in advance.
1
8
2k
Apr ’25
Need Help Updating a Custom WireGuard SPM for Xcode 16 & Swift 6
Hey iOS Dev's, I’m currently working on a Swift Package Manager (SPM) for WireGuard, originally developed by a previous team member. It was working fine in Xcode 15.2, but after upgrading to Xcode 16 and Swift 6, I need to update the SPM to ensure compatibility with my base projects and other projects relying on it. With Apple making Xcode 16 mandatory for app submissions starting April 24, this has become an urgent issue. I’ve searched extensively but haven’t found a working solution yet. Has anyone faced similar challenges with Swift 6 migration and SPM updates? Any insights, best practices, or debugging tips would be greatly appreciated! Let’s connect and collaborate—I’d love to discuss possible solutions! 😊 #iOSDevelopment #Swift6 #Xcode16 #SPM #WireGuard #iOS #Swift #SoftwareEngineering #AppStore
0
0
68
Apr ’25
How to use xcframework in SwiftPackage and statically link it into iOS product
I want to statically link xcframework as binaryTarget in Swift Package, but it is copied into the product as dynamic when the Xcode build. How to use xcframework in SwiftPackage and statically link it into iOS product? The Package.swift content and the project are: The WebP.xcframework is static: The Xcode Build Product's WebP.framework is dynamic:
0
0
66
Apr ’25
security policy does not allow @ path expansion
I’ve been working on a Catalyst version of my iOS apps. Finally everything is working apart from the custom intents the user user to configure the widgets. The config UI loads: And changing settings at this level works. But it can’t load the options for the other settings: “No options were provided for this parameter” I see this crash in the intent: Termination Reason: Namespace DYLD, Code 1 Library missing Library not loaded: @rpath/CocoaLumberjack.framework/Versions/A/CocoaLumberjack Referenced from: <E1BF4CC5-4181-3272-828C-86B1CD1A66BF> /Applications/my.app/Contents/PlugIns/Intents.appex/Contents/MacOS/Intents Reason: , (security policy does not allow @ path expansion) (terminated at launch; ignore backtrace) I have added the Hardened Runtime Capability to the Main App Target, the Widget Target and the Intents Target. I also allowed “Disable Library Validation” just in case. What am I missing?
5
0
216
Mar ’25
Active Compilation Conditions in Packages
The flags like #if DEBUG ... endif are dependent on the Active Compilation Conditions. So if they say DEBUG the enclosed code block will be executed, otherwise not. Now I have the phenomenon that a #DEBUG block in a Package does not evaluate these conditions. It rather depends on the name of the configuration used to build. So if I build my app with Active Compilation Condition set to DEBUG, but the configuration name is something like App-Release, the DEBUG block in my Package is not added/executed. The ones which are directly in the project are added. Vice versa if the Compilation Condition say RELEASE but the configuration is called App-Debug the blocks in the Package are added to the compilation, but the ones in the project itself are not It suffices that the config name contains the word Debug for this to happen. E.g. the configuration App-Release-Debug (I know that this would be stupid, but it is for demonstrating purposes) will cause the Packages to include the DEBUG blocks. This happens no matter what you set in the Build Settings of the project and/or target. The Packages are added via GitHub/GitLab Source Control with SPM. Any ideas why this behaves like it does? It doesn't seem like it should...
0
1
74
Mar ’25
Integrating binary inside Framework via SPM
So I will summary an issue one of our clients has asked us on GitHub: https://github.com/pendo-io/pendo-mobile-sdk/issues/233 Project that is a custom framework that uses different SPM packages (one of them is Binary package), we have our main logic inside that framework and we have different targets that use this framework, everything works on the simulator, but running the app on the actual device provokes a crash saying "Binary framework was not found". We have like 20 other SPM packages that work fine, this is the first one we have an issue with. Please note I understand that SPM will not copy paste the Binary for the magic framework as it does for the apps so I suggested to embed it manually. So my question is what the best(easy) way to do it. Please refer to the following issue for more details: https://github.com/pendo-io/pendo-mobile-sdk/issues/233
0
0
58
Mar ’25
URLSession works for request but not NWConnection
I am trying to convert a simple URLSession request in Swift to using NWConnection. This is because I want to make the request using a Proxy that requires Authentication. I posted this SO Question about using a proxy with URLSession. Unfortunately no one answered it but I found a fix by using NWConnection instead. Working Request func updateOrderStatus(completion: @escaping (Bool) -&gt; Void) { let orderLink = "https://shop.ccs.com/51913883831/orders/f3ef2745f2b06c6b410e2aa8a6135847" guard let url = URL(string: orderLink) else { completion(true) return } let cookieStorage = HTTPCookieStorage.shared let config = URLSessionConfiguration.default config.httpCookieStorage = cookieStorage config.httpCookieAcceptPolicy = .always let session = URLSession(configuration: config) var request = URLRequest(url: url) request.httpMethod = "GET" request.setValue("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", forHTTPHeaderField: "Accept") request.setValue("none", forHTTPHeaderField: "Sec-Fetch-Site") request.setValue("navigate", forHTTPHeaderField: "Sec-Fetch-Mode") request.setValue("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0.1 Safari/605.1.15", forHTTPHeaderField: "User-Agent") request.setValue("en-US,en;q=0.9", forHTTPHeaderField: "Accept-Language") request.setValue("gzip, deflate, br", forHTTPHeaderField: "Accept-Encoding") request.setValue("document", forHTTPHeaderField: "Sec-Fetch-Dest") request.setValue("u=0, i", forHTTPHeaderField: "Priority") // make the request } Attempted Conversion func updateOrderStatusProxy(completion: @escaping (Bool) -&gt; Void) { let orderLink = "https://shop.ccs.com/51913883831/orders/f3ef2745f2b06c6b410e2aa8a6135847" guard let url = URL(string: orderLink) else { completion(true) return } let proxy = "resi.wealthproxies.com:8000:akzaidan:x0if46jo-country-US-session-7cz6bpzy-duration-60" let proxyDetails = proxy.split(separator: ":").map(String.init) guard proxyDetails.count == 4, let port = UInt16(proxyDetails[1]) else { print("Invalid proxy format") completion(false) return } let proxyEndpoint = NWEndpoint.hostPort(host: .init(proxyDetails[0]), port: NWEndpoint.Port(integerLiteral: port)) let proxyConfig = ProxyConfiguration(httpCONNECTProxy: proxyEndpoint, tlsOptions: nil) proxyConfig.applyCredential(username: proxyDetails[2], password: proxyDetails[3]) let parameters = NWParameters.tcp let privacyContext = NWParameters.PrivacyContext(description: "ProxyConfig") privacyContext.proxyConfigurations = [proxyConfig] parameters.setPrivacyContext(privacyContext) let host = url.host ?? "" let path = url.path.isEmpty ? "/" : url.path let query = url.query ?? "" let fullPath = query.isEmpty ? path : "\(path)?\(query)" let connection = NWConnection( to: .hostPort( host: .init(host), port: .init(integerLiteral: UInt16(url.port ?? 80)) ), using: parameters ) connection.stateUpdateHandler = { state in switch state { case .ready: print("Connected to proxy: \(proxyDetails[0])") let httpRequest = """ GET \(fullPath) HTTP/1.1\r Host: \(host)\r Connection: close\r Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0.1 Safari/605.1.15\r Accept-Language: en-US,en;q=0.9\r Accept-Encoding: gzip, deflate, br\r Sec-Fetch-Dest: document\r Sec-Fetch-Mode: navigate\r Sec-Fetch-Site: none\r Priority: u=0, i\r \r """ connection.send(content: httpRequest.data(using: .utf8), completion: .contentProcessed({ error in if let error = error { print("Failed to send request: \(error)") completion(false) return } // Read data until the connection is complete self.readAllData(connection: connection) { finalData, readError in if let readError = readError { print("Failed to receive response: \(readError)") completion(false) return } guard let data = finalData else { print("No data received or unable to read data.") completion(false) return } if let body = String(data: data, encoding: .utf8) { print("Received \(data.count) bytes") print("\n\nBody is \(body)") completion(true) } else { print("Unable to decode response body.") completion(false) } } })) case .failed(let error): print("Connection failed for proxy \(proxyDetails[0]): \(error)") completion(false) case .cancelled: print("Connection cancelled for proxy \(proxyDetails[0])") completion(false) case .waiting(let error): print("Connection waiting for proxy \(proxyDetails[0]): \(error)") completion(false) default: break } } connection.start(queue: .global()) } private func readAllData(connection: NWConnection, accumulatedData: Data = Data(), completion: @escaping (Data?, Error?) -&gt; Void) { connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { data, context, isComplete, error in if let error = error { completion(nil, error) return } // Append newly received data to what's been accumulated so far let newAccumulatedData = accumulatedData + (data ?? Data()) if isComplete { // If isComplete is true, the server closed the connection or ended the stream completion(newAccumulatedData, nil) } else { // Still more data to read, so keep calling receive self.readAllData(connection: connection, accumulatedData: newAccumulatedData, completion: completion) } } }
3
0
455
Mar ’25
Use native Swift API for HTTP request with auth proxy
I'm simply trying to use a proxy to route a http request in Swift. I've tried using a URLSession Delegate but that results in the same issue with the iOS menu. proxy format: host:port:username:password When I run the code below I am prompted with a menu to add credentials for the proxy. I closed this menu inside my app and tried the function below again and it worked without giving me the menu a second time. However even though the function works without throwing any errors, it does NOT use the proxies to route the request. I've spent days on this and the only solution I found was using a NWConnection but this is super low level and now I need a shared session to manage cookies. If you want to see the NWConnection solution I made its here func averageProxyGroupSpeed(proxies: [String], completion: @escaping (Int, String) -> Void) { let numProxies = proxies.count if numProxies == 0 { completion(0, "No proxies") return } var totalTime: Int64 = 0 var successCount = 0 let group = DispatchGroup() let queue = DispatchQueue(label: "proxyQueue", attributes: .concurrent) let lock = NSLock() let shuffledProxies = proxies.shuffled() let selectedProxies = Array(shuffledProxies.prefix(25)) for proxy in selectedProxies { group.enter() queue.async { let proxyDetails = proxy.split(separator: ":").map(String.init) guard proxyDetails.count == 4, let port = Int(proxyDetails[1]), let url = URL(string: "http://httpbin.org/get") else { completion(0, "Invalid proxy format") group.leave() return } var request = URLRequest(url: url) request.timeoutInterval = 15 let configuration = URLSessionConfiguration.default configuration.connectionProxyDictionary = [ AnyHashable("HTTPEnable"): true, AnyHashable("HTTPProxy"): proxyDetails[0], AnyHashable("HTTPPort"): port, AnyHashable("HTTPSEnable"): false, AnyHashable("HTTPUser"): proxyDetails[2], AnyHashable("HTTPPassword"): proxyDetails[3] ] let session = URLSession(configuration: configuration) let start = Date() let task = session.dataTask(with: request) { _, _, error in defer { group.leave() } if let error = error { print("Error: \(error.localizedDescription)") } else { let duration = Date().timeIntervalSince(start) * 1000 lock.lock() totalTime += Int64(duration) successCount += 1 lock.unlock() } } task.resume() } } group.notify(queue: DispatchQueue.main) { if successCount == 0 { completion(0, "Proxies Failed") } else { let averageTime = Int(Double(totalTime) / Double(successCount)) completion(averageTime, "") } } } Delegate example class ProxySessionDelegate: NSObject, URLSessionDelegate { let username: String let password: String init(username: String, password: String) { self.username = username self.password = password } func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic { let credential = URLCredential(user: self.username, password: self.password, persistence: .forSession) completionHandler(.useCredential, credential) } else { completionHandler(.performDefaultHandling, nil) } } }
2
0
386
Mar ’25