Hi.
I have a xcframework that has a dependency on 'RxSwift' and 'RxCocoa'. I deployed it using SPM by embedding it in a Swift Package.
However when I import swift package into another project, I keep getting the following error:
"Missing required module 'RxCocoaRuntime"
How can I fix this?
Below are the steps to reproduce the error.
Steps
Create Xcode proejct, make a dependency on 'RxSwift' and 'RxCocoa' (no matter doing it through tuist or cocoapods)
Create XCFramework from that proejct. (I used commands below)
xcodebuild archive \
-workspace SimpleFramework.xcworkspace \
-scheme "SimpleFramework" \
-destination "generic/platform=iOS" \
-archivePath "./SimpleFramework-iphoneos.xcarchive" \
-sdk iphoneos \
SKIP_INSTALL=NO \
BUILD_LIBRARY_FOR_DISTRIBUTION=YES
xcodebuild archive \
-workspace SimpleFramework.xcworkspace \
-scheme "SimpleFramework" \
-archivePath "./SimpleFramework-iphonesimulator.xcarchive" \
-sdk "iphonesimulator" \
SKIP_INSTALL=NO \
BUILD_LIBRARY_FOR_DISTRIBUTION=YES
xcodebuild -create-xcframework \
-framework "./SimpleFramework-iphoneos.xcarchive/Products/Library/Frameworks/SimpleFramework.framework" \
-framework "./SimpleFramework-iphonesimulator.xcarchive/Products/Library/Frameworks/SimpleFramework.framework" \
-output "./SimpleFramework.xcframework"
Embed in Swift Package, and deploy.
// swift-tools-version: 6.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "SimplePackage",
platforms: [.iOS(.v16)],
products: [
.library(
name: "SimplePackage",
targets: ["SimplePackage"]),
],
dependencies: [
.package(url: "https://github.com/ReactiveX/RxSwift", from: "6.8.0")
],
targets: [
.binaryTarget(
name: "SimpleFramework",
path: "Sources/SimpleFramework.xcframework"
),
.target(
name: "SimplePackage",
dependencies: [
"SimpleFramework",
"RxSwift",
.product(name: "RxCocoa", package: "RxSwift")
]
)
]
)
Download Swift Package in another project and import module.
I resolved this by removing dependencies from the Swift Package, downloading package in another project, and fetching dependencies by cocoapods.
Thist works, but I don't want to use another dependency manager while using SPM.
Development Environment
CPU : Apple M4 Max
MacOS : Sequoia 15.3
Xcode : 16.2
How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here
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
I'm trying to improve my build time on macOS by not building for x86_64. I've got the following settings:
This gets Xcode not to build x86_64 for my app, but not all the package dependencies.
I've updated most of the packages to swift-tools-version: 6.0 but FlatBuffers is still on 5.8 and .macOS(.v10_14). GPT claims:
If your deployment target is set to macOS 10.15 or earlier, Xcode may force x86_64 support for compatibility reasons.
But Xcode is building x86_64 for ALL my packages, even the ones that don't depend on FlatBuffers.
When I open a package in Xcode that depends on FlatBuffers, then it builds arm only, so that may be a red herring.
Not sure what else to try.
I had several library projects that were working in Swift Playgrounds < 4.6 but I get several duplicate compilation errors and previews will not build in Swift Playgrounds > 4.6. Does anyone know how to fix this issue?
Example project:
This project builds and runs fine under Swift Playgrounds 4.5.1 however it will not run complaining multiple commands produce generated output files under Swift Playgrounds 4.6.1, 4.6.2, and 4.6.3.
https://github.com/kudit/Compatibility
Download this repository and add the extension ".swiftpm" to the folder and double click to open in Swift Playgrounds. If running on earlier Swift Playgrounds you can see there are no errors and previews work great (on both macOS and iPadOS versions of Swift Playgrounds 4.5.x). However, on Swift Playgrounds 4.6.x, previews will not display.
Are embedded libraries not support anymore? This would be very disappointing.
I posted this as a Feedback weeks ago with no response: FB16509699
Topic:
Developer Tools & Services
SubTopic:
Swift Playground
Tags:
Swift Packages
Swift Playground
Playground Support
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)
}
}
}
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!
Topic:
Developer Tools & Services
SubTopic:
Xcode
Tags:
Swift Packages
Developer Tools
Frameworks
Compiler
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
Topic:
Media Technologies
SubTopic:
Photos & Camera
Tags:
Swift Packages
App Clips
Developer Tools
iOS
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 ?
Topic:
Developer Tools & Services
SubTopic:
Xcode
Tags:
Swift Packages
Developer Tools
Xcode Previews
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?
Topic:
Accessibility & Inclusion
SubTopic:
General
Tags:
Swift Packages
Messages
Xcode
Group Activities
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!
Topic:
Developer Tools & Services
SubTopic:
General
Tags:
Swift Packages
Swift Student Challenge
Swift Playground
Visual Design
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.
Topic:
Developer Tools & Services
SubTopic:
Swift Playground
Tags:
Swift Packages
Swift
Swift Playground