Hello everyone,
I’m encountering an issue when trying to build and archive my library BleeckerCodesLib using Swift Package Manager. My project is structured with two targets:
CBleeckerLib: A C target that contains my image processing code (C source files and public headers).
BleeckerCodesLib: A Swift target that depends on CBleeckerLib and performs an import CBleeckerLib.
Below is the relevant portion of my Package.swift:
// swift-tools-version:5.7
import PackageDescription
let package = Package(
name: "BleeckerCodesLib",
platforms: [.iOS(.v16)],
products: [
.library(name: "BleeckerCodesLib", targets: ["BleeckerCodesLib"])
],
targets: [
.target(
name: "CBleeckerLib",
publicHeadersPath: "include"
),
.target(
name: "BleeckerCodesLib",
dependencies: ["CBleeckerLib"]
)
]
)
Directory Structure
My project directory looks like this:
BleeckerCodesLib/
├── BleeckerCodesLib.xcodeproj/
│ └── xcuserdata/
│ └── robertopitarch.xcuserdatad/
│ └── xcschemes/
│ └── xcschememanagement.plist
├── BleeckerCodesLib.h
├── Package.swift
└── Sources/
├── CBleeckerLib/
│ ├── bleecker-lib.c
│ └── include/
│ ├── bleecker-lib.h
│ └── CBleeckerLib.h
└── BleeckerCodesLib/
├── UIImage+Extensions.swift
├── ImageProcessingUtility.swift
├── APIManager.swift
├── BleeckerCodesLib.swift
├── CameraView.swift
├── RealTimeCameraView.swift
└── BleeckerCameraWrapper.swift
Code Example
In my Swift code (for example, in BleeckerCodesLib.swift), I import the C module as follows:
import SwiftUI
import UIKit
import CBleeckerLib // Import the C module
public struct BleeckerCodes {
public struct DetectedCode {
public let code: String
public let corners: [CGPoint]
public init(code: String, corners: [CGPoint]) {
self.code = code
self.corners = corners
}
}
// Initialization function
public static func initializeLibrary() -> String {
bleecker_init() // Call the C module function
return "BleeckerCodesLibrary initialized!"
}
// ... other functions
}
The Problem
When I try to compile or archive the project using commands such as:
xcodebuild archive -project BleeckerCodesLib.xcodeproj -scheme BleeckerCodesLib -destination "generic/platform=iOS" -archivePath "archives/BleeckerCodesLib"
I receive the error: "no such module 'CBleeckerLib'"
Any assistance or step-by-step guidance on resolving this integration issue would be greatly appreciated.
Thank you in advance!
Swift Packages
RSS for tagCreate 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
My project uses a local swift package of my own, which uses SwiftGenPlugin to generate image resources. I can archive the project locally, but Xcode Cloud doesn't work and reports an error: "SwiftGenPlugin" is disabled.
HI,
swiftdata is new to me and any help would be appreciated.
In my swiftui app I have a functionality that reinstates the database from an archive.
I first move the three database files (database.store datebase.store-wal and database.store-shm) to a new name (.tmp added for backup incase) and then copy the Archived three files to the same location.
the move creates the following errors:
" BUG IN CLIENT OF libsqlite3.dylib: database integrity compromised by API violation: vnode renamed while in use: /private/var/mobile/Containers/Data/Application/499A6802-02E5-4547-83C4-88389AEA50F5/Library/Application Support/database.store.tmp
invalidated open fd: 4 (0x20)"
I get the same message in console for all three files.
then I reinitialise the model container and get no errors as my code below
....
let schema = Schema([....my different models are here])
let config = ModelConfiguration("database", schema: schema)
do {
// Recreate the container with the same store URL
let container = try ModelContainer(for: schema, configurations: config)
print("ModelContainer reinitialized successfully!")
} catch {
print("Failed to reinitialize ModelContainer: (error)")
}
}
I get the success message but when I leave the view (backup-restore view) to the main view I get:
CoreData: error: (6922) I/O error for database at /var/mobile/Containers/Data/Application/499A6802-02E5-4547-83C4-88389AEA50F5/Library/Application Support/database.store. SQLite error code:6922, 'disk I/O error'
and
error: SQLCore dispatchRequest: exception handling request: <NSSQLFetchRequestContext: 0x302920460> , I/O error for database at /var/mobile/Containers/Data/Application/499A6802-02E5-4547-83C4-88389AEA50F5/Library/Application Support/database.store. SQLite error code:6922, 'disk I/O error' with userInfo of {
NSFilePath = "/var/mobile/Containers/Data/Application/499A6802-02E5-4547-83C4-88389AEA50F5/Library/Application Support/database.store";
NSSQLiteErrorDomain = 6922;
}
error: -executeRequest: encountered exception = I/O error for database at /var/mobile/Containers/Data/Application/499A6802-02E5-4547-83C4-88389AEA50F5/Library/Application Support/database.store. SQLite error code:6922, 'disk I/O error' with userInfo = {
NSFilePath = "/var/mobile/Containers/Data/Application/499A6802-02E5-4547-83C4-88389AEA50F5/Library/Application Support/database.store";
NSSQLiteErrorDomain = 6922;
}
CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLFetchRequestContext: 0x302920460> , I/O error for database at /var/mobile/Containers/Data/Application/499A6802-02E5-4547-83C4-88389AEA50F5/Library/Application Support/database.store. SQLite error code:6922, 'disk I/O error' with userInfo of {
NSFilePath = "/var/mobile/Containers/Data/Application/499A6802-02E5-4547-83C4-88389AEA50F5/Library/Application Support/database.store";
NSSQLiteErrorDomain = 6922;
}
Can anyone let me know how I should go about this - reseting the database from old backup files by copying over them.
or if there is a way to stop the database and restart it with the new files in swiftdata
my app is an ios app for phone and ipad
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
I've encountered an issue where using @Observable in SwiftUI causes extra initializations and deinitializations when a reference type is included as a property inside a struct. Specifically, when I include a reference type (a simple class Empty {}) inside a struct (Test), DetailsViewModel is initialized and deinitialized twice instead of once. If I remove the reference type, the behavior is correct.
This issue does not occur when using @StateObject instead of @Observable. Additionally, I've submitted a feedback report: FB16631081.
Steps to Reproduce
Run the provided SwiftUI sample code (tested on iOS 18.2 & iOS 18.3 using Xcode 16.2).
Observe the console logs when navigating to DetailsView.
Comment out var empty = Empty() in the Test struct.
Run again and compare console logs.
Change @Observable in DetailsViewModel to @StateObject and observe that the issue no longer occurs.
Expected Behavior
The DetailsViewModel should initialize once and deinitialize once, regardless of whether Test contains a reference type.
Actual Behavior
With var empty = Empty() present, DetailsViewModel initializes and deinitializes twice. However, if the reference type is removed, or when using @StateObject, the behavior is correct (one initialization, one deinitialization).
Code Sample
import SwiftUI
enum Route {
case details
}
@MainActor
@Observable
final class NavigationManager {
var path = NavigationPath()
}
struct ContentView: View {
@State private var navigationManager = NavigationManager()
var body: some View {
NavigationStack(path: $navigationManager.path) {
HomeView()
.environment(navigationManager)
}
}
}
final class Empty { }
struct Test {
var empty = Empty() // Comment this out to make it work
}
struct HomeView: View {
private let test = Test()
@Environment(NavigationManager.self) private var navigationManager
var body: some View {
Form {
Button("Go To Details View") {
navigationManager.path.append(Route.details)
}
}
.navigationTitle("Home View")
.navigationDestination(for: Route.self) { route in
switch route {
case .details:
DetailsView()
.environment(navigationManager)
}
}
}
}
@MainActor
@Observable
final class DetailsViewModel {
var fullScreenItem: Item?
init() {
print("DetailsViewModel Init")
}
deinit {
print("DetailsViewModel Deinit")
}
}
struct Item: Identifiable {
let id = UUID()
let value: Int
}
struct DetailsView: View {
@State private var viewModel = DetailsViewModel()
@Environment(NavigationManager.self) private var navigationManager
var body: some View {
ZStack {
Color.green
Button("Show Full Screen Cover") {
viewModel.fullScreenItem = .init(value: 4)
}
}
.navigationTitle("Details View")
.fullScreenCover(item: $viewModel.fullScreenItem) { item in
NavigationStack {
FullScreenView(item: item)
.navigationTitle("Full Screen Item: \(item.value)")
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") {
withAnimation(completionCriteria: .logicallyComplete) {
viewModel.fullScreenItem = nil
} completion: {
var transaction = Transaction()
transaction.disablesAnimations = true
withTransaction(transaction) {
navigationManager.path.removeLast()
}
}
}
}
}
}
}
}
}
struct FullScreenView: View {
@Environment(\.dismiss) var dismiss
let item: Item
var body: some View {
ZStack {
Color.red
Text("Full Screen View \(item.value)")
.navigationTitle("Full Screen View")
}
}
}
Console Output
With var empty = Empty() in Test
DetailsViewModel Init
DetailsViewModel Init
DetailsViewModel Deinit
DetailsViewModel Deinit
Without var empty = Empty() in Test
DetailsViewModel Init
DetailsViewModel Deinit
Using @StateObject Instead of @Observable
DetailsViewModel Init
DetailsViewModel Deinit
Additional Notes
This issue occurs only when using @Observable. Switching to @StateObject prevents it. This behavior suggests a possible issue with how SwiftUI handles reference-type properties inside structs when using @Observable.
Using a struct-only approach (removing Empty class) avoids the issue, but that’s not always a practical solution.
Questions for Discussion
Is this expected behavior with @Observable?
Could this be an unintended side effect of SwiftUI’s state management?
Are there any recommended workarounds apart from switching to @StateObject?
Would love to hear if anyone else has run into this or if Apple has provided any guidance!
Swift Package:
I have an old objc library, that is added as XCFramework to swift package as a binary target.
targets: [
.target(
name: "CoreServices",
dependencies: ["OldContainer"],
path: "CoreServices"
),
.binaryTarget(
name: "OldContainer",
path: "Frameworks/OldContainer.xcframework"
),
]
This serves the purpose, it builds fine and able to run on simulator. However this framework is breaking the Xcode previews.
Error:
== PREVIEW UPDATE ERROR:
[Remote] JITError: Runtime linking failure
Additional Link Time Errors:
Symbols not found: [ _OBJC_CLASS_$_SCSecureServicesFactory ]
==================================
| [Remote] LLVMError
|
| LLVMError: LLVMError(description: "Failed to materialize symbols: { (static-Login, { __replacement_tag$1015 }) }")
== VERSION INFO:
Tools: 16C5032a
OS: 23G93
PID: 38675
Model: MacBook Pro
Arch: arm64e
== ENVIRONMENT:
openFiles = [
/Users/../Documents/GitHub/Packages/Login/Sources/Login/LoginView.swift
]
wantsNewBuildSystem = true
newBuildSystemAvailable = true
activeScheme = Launch
activeRunDestination = iPhone 16 Pro Max variant iphonesimulator arm64
workspaceArena = [x]
buildArena = [x]
buildableEntries = [
Login
Login
]
runMode = JIT Executor
== SELECTED RUN DESTINATION:
Simulator - iOS 18.2 | iphonesimulator | arm64 | iPhone 16 Pro Max | no proxy
== EXECUTION MODE OVERRIDES:
Workspace JIT mode user setting: true
Falling back to Dynamic Replacement: false
Based on the error, SCSecureServicesFactory is an objc file inside the XCFramework. Since this is a binary target, I could not add a swift setting module map flag to the XCFramework.
Is there any workaround to get the previews working ? Or Am I blocked until the library is converted into swift ?
I am encountering the following issue while working with app group preferences in my Safari web extension:
Couldn't read values in CFPrefsPlistSource<0x3034e7f80> (Domain: [MyAppGroup], User: kCFPreferencesAnyUser, ByHost: Yes, Container: (null), Contents Need Refresh: Yes): Using kCFPreferencesAnyUser with a container is only allowed for System Containers, detaching from cfprefsd.
I am trying to read/write shared preferences using UserDefaults with an App Group but keep running into this error. Any guidance on how to resolve this would be greatly appreciated!
Has anyone encountered this before? How can I properly configure my app group preferences to avoid this issue?
Dear Apple Developer Support,
I am writing to request assistance with an ongoing issue I'm encountering while developing an iOS application that utilizes HealthKit to fetch heart rate data.
My goal is to display near real-time heart rate updates continuously same as displaying in the Apple Watch , I want to show in the iPhone Mobile Application for fitness related. I have implemented the following approaches:
HKSampleQuery with a Timer: I've set up a timer to periodically fetch the latest heart rate data.
Despite these efforts, I'm consistently facing the following problems:
Delayed Updates: The heart rate data displayed in the app often doesn't reflect the current heart rate being measured by the Apple Watch. There seems to be a significant synchronization delay.
Inconsistent Background Updates: Background updates, even with background app refresh enabled, are not reliable. The app often only updates when brought to the foreground or after being killed and relaunched.
Entitlements: The com.apple.developer.healthkit.background-delivery entitlement error is missing.
I have thoroughly reviewed Apple's HealthKit documentation, implemented best practices for HealthKit integration, and verified that all necessary permissions are properly configured.
I understand that HealthKit may not be designed for true real-time data, but the current level of delay and inconsistency is making it difficult to provide a useful user experience.
Could you please provide guidance on whether achieving near real-time heart rate updates continuously in an iOS app using HealthKit is possible? If so, what are the recommended strategies and best practices to overcome these limitations?
I have also tested the application on physical devices with Apple Watch, enabled background app refresh, granted permissions, and referred to HealthKit documentation.
I would appreciate any insights or suggestions you can offer to help resolve this issue.
Thank you for your time and assistance.
Sincerely,
Venu Madhav
We are currently running a lightweight server within our iOS mobile app to pass a unique device ID via localhost for device-based restrictions. The setup works by binding a user's email to their device ID upon login, and later, when they attempt to log in via a browser, we retrieve this ID by making a request to http://localhost:8086/device-info.
However, we're encountering an issue when making this request. Here’s the error message:
Error fetching device info: TypeError { }
r@webkit-masked-url://hidden/:27:166011
value@webkit-masked-url://hidden/:27:182883
@webkit-masked-url://hidden/:27:184904
We are making this request from an HTTPS website, and we suspect this could be related to mixed-content restrictions. Could you guide us on how to properly make localhost requests over HTTPS, especially in a production environment with the necessary security measures?
Any insights or best practices on resolving this issue would be greatly appreciated.
My question is simple, I do not have much experience in writing swift code, I am only doing it to create a small executable that I can call from my python application which completes Subcription Management.
I was hoping someone with more experience could point out my flaws along with giving me tips on how to verify that the check is working for my applicaiton. Any inight is appreciated, thank you.
import Foundation
import StoreKit
class SubscriptionValidator {
static func getReceiptURL() -> URL? {
guard let appStoreReceiptURL = Bundle.main.appStoreReceiptURL else {
print("No receipt found.")
return nil
}
return appStoreReceiptURL
}
static func validateReceipt() -> Bool {
guard let receiptURL = getReceiptURL(),
let receiptData = try? Data(contentsOf: receiptURL) else {
print("Could not read receipt.")
return false
}
let receiptString = receiptData.base64EncodedString()
let validationResult = sendReceiptToApple(receiptString: receiptString)
return validationResult
}
static func sendReceiptToApple(receiptString: String) -> Bool {
let isSandbox = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
let urlString = isSandbox ? "https://sandbox.itunes.apple.com/verifyReceipt" : "https://buy.itunes.apple.com/verifyReceipt"
let url = URL(string: urlString)!
let requestData: [String: Any] = [
"receipt-data": receiptString,
"password": "0b7f88907b77443997838c72be52f5fc"
]
guard let requestBody = try? JSONSerialization.data(withJSONObject: requestData) else {
print("Error creating request body.")
return false
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = requestBody
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let semaphore = DispatchSemaphore(value: 0)
var isValid = false
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil,
let jsonResponse = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let status = jsonResponse["status"] as? Int else {
print("Receipt validation failed.")
semaphore.signal()
return
}
if status == 0, let receipt = jsonResponse["receipt"] as? [String: Any],
let inApp = receipt["in_app"] as? [[String: Any]] {
for purchase in inApp {
if let expiresDateMS = purchase["expires_date_ms"] as? String,
let expiresDate = Double(expiresDateMS) {
let expiryDate = Date(timeIntervalSince1970: expiresDate / 1000.0)
if expiryDate > Date() {
isValid = true
}
}
}
}
semaphore.signal()
}
task.resume()
semaphore.wait()
return isValid
}
}
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) -> 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) -> 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?) -> 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)
}
}
}
I'm simply trying to use a proxy to route a http request in Swift to measure the average round trip time of a list of proxies. I've went through multiple Stack Overflow threads on this topic but they are all super old / outdated.
format:host:port:username:password
I also added the info.plist entry:
NSAllowsArbitraryLoads -> NSExceptionDomains
When I call the function below I am prompted with a menu that says
"Proxy authentication required. Enter the password for HTTP proxy ... in settings"
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.
Why does the request work (throws no errors) but does not use the proxies? I'm assuming it's because the password isn't entered in the settings as the alert said. My users will want to test proxy speeds for many different Hosts/Ports, it doesn't make sense to enter the password in settings every time. How can I fix this issue?
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, "")
}
}
}
So the battery level value is in accurate returns the battery percentage in multiple of 5 values e.g. battery percentage is 42 but the api returns it as 40. So please fix the issue if possible because i checked that the
devices running iOS versions below 17 appear to be working fine.
Hi! I wanted to use Lottie in my swiftpm app, but I've been running into errors and I'm not sure if it's possible. When I try to run the app, it crashes and I get errors saying that the library isn't loaded and the files aren't found (basically these: https://github.com/lottie-react-native/lottie-react-native/issues/373 , https://github.com/airbnb/lottie-ios/issues/2233 ). But moving the framework file into the PackageFrameworks folder doesn't work, and also I'm getting the error that swiftpm cannot distribute packages containing binary frameworks and from what I understand that just isn't something that swiftpm can do. So I was wondering if anyone knows any workarounds to this, or if I should just ditch Lottie?
Any help or advice would be greatly appreciated!
When I created a search box on the homepage, I was able to enter text in the input field while previewing in Xcode. However, after clicking "Build" and running the app, I couldn't type anything into the input field in the demo interface. Additionally, I received the following error message:
If you want to see the backtrace, please set CG_NUMERICS_SHOW_BACKTRACE environmental variable.
Error: this application, or a library it uses, has passed an invalid numeric value (NaN, or not-a-number) to CoreGraphics API and this value is being ignored. Please fix this problem.
How can I fix this issue?
Here is my ContentView.swift code:
import SwiftUI
struct ContentView: View {
@State private var searchText: String = ""
@State private var isSearching: Bool = false
var body: some View {
NavigationStack {
GeometryReader { geometry in
VStack {
Spacer()
.frame(height: geometry.size.height.isNaN ? 0 : geometry.size.height * 0.3)
VStack(spacing: 20) {
Text("NMFC CODES LOOKUP")
.font(.title2)
.bold()
TextField("Search...", text: $searchText)
.textFieldStyle(PlainTextFieldStyle())
.padding(10)
.frame(height: 40)
.frame(width: geometry.size.width.isNaN ? 0 : geometry.size.width * 0.9)
.background(Color.white)
.cornerRadius(8)
.overlay(
HStack {
Spacer()
if !searchText.isEmpty {
Button(action: {
searchText = ""
}) {
Image(systemName: "xmark.circle.fill")
.foregroundColor(.gray)
.padding(.trailing, 8)
}
}
}
)
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(Color.gray.opacity(0.5), lineWidth: 1)
)
Button(action: {
isSearching = true
}) {
Text("Search")
.foregroundColor(.white)
.frame(width: geometry.size.width * 0.9, height: 40)
.background(Color.blue)
.cornerRadius(8)
}
.disabled(searchText.isEmpty)
Text("Created & Designed & Developed By Matt")
.font(.caption)
.foregroundColor(.gray)
.padding(.top, 10)
}
Spacer()
.frame(height: geometry.size.height * 0.7)
}
.frame(width: geometry.size.width)
}
.background(Color(red: 250/255, green: 245/255, blue: 240/255))
.navigationDestination(isPresented: $isSearching) {
SearchResultsView(searchQuery: searchText)
}
}
.background(Color(red: 250/255, green: 245/255, blue: 240/255))
.ignoresSafeArea()
}
}
#Preview {
ContentView()
}
Fatal Error in Swift Playground
Description
I'm experiencing a catastrophic error when importing Package Dependency in any Swift Playgrounds that has icon or name that caused the whole Playground won't work anymore with error messages below.
I'm current running macOS Sequoia 15.3 (24D60) and Swift Playgrounds 4.6.1. They're all up-to-date.
Reproduction
Open Swift Playgrounds and and create a new project.
Import a package dependency
https://github.com/simibac/ConfettiSwiftUI.git
Rename the project and add an icon
Then you should able the reproduce the problem. I strongly believed that this is a serious bug.
You'll find that Assets in the left column are disappeared and appeared Assets.xcassets, you're unable to reveal the Dependency in the column like the reference picture above. The whole Playground is destroyed now and unable to work anymore.
When test support code relies on production code, a diamond can occur. If this occurs across packages, it can lead to duplicated symbols and incorrect behavior at runtime despite no warnings at build time. This only occurs in Xcode and top-level application testing. This doesn't occur when the code being tested is in a separate package.
I'm trying to understand how to correctly manage shared test support code which needs to access production code, or if this is the correct way and it is an Xcode bug.
For a minimized example project, see https://github.com/rnapier/SupportCode.
The setup includes three packages: Dependencies, which manages all the dependencies for the app and tests; Core which contains core logic and test support; and Feature, which relies on Core an contains feature-related logic and test support.
Building this system causes Core.framework to show up three times in DerivedData:
./App.app/PlugIns/AppTests.xctest/Frameworks/Core_59974D35D_PackageProduct.framework
./App.app/Frameworks/Core_59974D35D_PackageProduct.framework
./PackageFrameworks/Core_59974D35D_PackageProduct.framework
When unit tests are run, there is a collision on the symbol for Keychain:
objc[48914]: Class _TtC8Keychain8Keychain is implemented in both /Users/ornapier/Library/Developer/Xcode/DerivedData/App-grdjljgevqofhqgflgtrqvhvbtej/Build/Products/Debug-iphonesimulator/PackageFrameworks/Core_59974D35D_PackageProduct.framework/Core_59974D35D_PackageProduct (0x100a98118) and /Users/ornapier/Library/Developer/CoreSimulator/Devices/216C441E-4AE5-45EC-8E52-FA42D8562365/data/Containers/Bundle/Application/7197F2F2-EB26-42FF-B7DB-67116159897D/App.app/PlugIns/AppTests.xctest/AppTests (0x1011002c0). One of the two will be used. Which one is undefined.
This is not a benign warning. There are two distinct copies of _TtC8Keychain8Keychain and test cases will access one and the app will access a different one. This leads to mismatches when accessing static instances such as .shared.
I believe this dependency graph should work, and it does work as long as the top-level testing system is a Swift module. But if it is the application, it builds successfully, but behaves incorrectly in subtle ways.
My organization just started having problems with Xcode Cloud this week.
We have created a pretty simple 'Build on Pull Request'. The problem is our builds have started failing immediately because with the error.
"Could not resolve package dependencies:"
What is even more frustrating is the dependency that reported failed seem to changes every time.
This did not happen before this week.
Our build process is fairly vanilla, through Xcode. (We are NOT using CLI xcodebuild)
I can build a locally just fine from a clean build, and cleaning derived data.
Nothing has changed in our dependencies.
We are not using any private dependencies.
So I am stumped on what else to do how to debug, and fix this, because I am not sure how to encourage the Xcode Cloud build runner/server that the dependences are available and to jsut go get them.
Any help would be great, because we just started using Xcode Cloud to get away from Fastlane (which was causing problems), and it would be frustrating if this is a sign of things to come.
Sincerely,
Stan
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
I have a working Xcode Cloud setup for my iOS and macOS targets, and I'm trying to add visionOS support. The issue is that Firebase requires using their source distribution for visionOS (instead of their default binary distribution).
Locally, this works by launching Xcode with:
open -a Xcode --env FIREBASE_SOURCE_FIRESTORE project.xcodeproj
For Xcode Cloud, I've added a ci_post_clone.sh script that sets this environment variable for visionOS builds:
#!/bin/bash
if [[ $CI_PRODUCT_PLATFORM == "xrOS" ]]; then
echo "Running setup for visionOS..."
export FIREBASE_SOURCE_FIRESTORE=1
fi
However, I'm getting the following error during build:
an out-of-date resolved file was detected at /.../project.xcworkspace/xcshareddata/swiftpm/Package.resolved, which is not allowed when automatic dependency resolution is disabled
So since setting FIREBASE_SOURCE_FIRESTORE=1 changes which SPM dependencies are required:
Normal setup uses: abseil-cpp-binary, grpc-binary
Source distribution needs: abseil-cpp-swiftpm, grpc-ios, boringssl-swiftpm
What's the recommended way to handle this in Xcode Cloud when maintaining builds for all platforms? Should I be using separate workflows with different branches for different platforms? Or is there a better approach?
System:
Xcode 16.2
Using SPM for dependency management
Firebase iOS SDK 10.29.0
Building for iOS, macOS, and visionOS
Thanks in advance for any guidance!