I am looking for a lightweight server that can run inside an app.
The key requirement is that it must support local IP communication over HTTPS.
I have searched Google and found several frameworks, but as far as I know, support for HTTPS in this environment has been discontinued or is no longer available.
If anyone knows a solution that meets these criteria, I would greatly appreciate your guidance.
Thank you in advance!😀
Networking
RSS for tagExplore the networking protocols and technologies used by the device to connect to Wi-Fi networks, Bluetooth devices, and cellular data services.
Post
Replies
Boosts
Views
Activity
I'm using the NEHotspostConfigurationManager to join the WiFi network of a configured accessory.
While this is all nice and dandy, I wonder why I'm still connected to said WiFi when I (force-)close the app. Wouldn't it be more useful to reconnect to the last network before?
Apps made through .net maui don't work with local networks.
I'm using the .net 8 framework, and I followed the app to the ios system through .net Maui after connecting it to the computer through a data cable.
When I open the app, I get a request to access the local network and I agree to it. But still my app is not accessible.
I have asserted it correctly inside info.plist.
How can I fix this issue
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, "")
}
}
}
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)
}
}
}
Dear Apple:
We encountered a problem when using the Wi-Fi connection feature. When calling the Wi-Fi connection interface NEHotspotConfigurationManager applyConfiguration, it fails probabilistically. After analyzing the air interface packets, it appears that the Apple device did not send the auth message. How should we locate this issue? Are there any points to pay attention to when calling the Wi-Fi connection interface? Thanks
When using ssidPrefix in the descriptor and completing the AccessorySetupKit setup, I attempt to connect to the accessory's Wi-Fi hotspot using NEHotspotConfigurationManager joinAccessoryHotspot.
The connection fails with the following error:
Error Domain=NEHotspotConfigurationErrorDomain Code=1 "invalid SSID." UserInfo={NSLocalizedDescription=invalid SSID.}
I'm using a prefix that is at least 3 characters.
If I provide ssid instead of ssidPrefix it connects successfully.
I am wondering wether iOS allow apps to detect users' proxy.
I'm writing an LDAP Browser app using SwiftUI. I tested my LDAP code using a command line app that uses the exact same libraries and it successfully connects to my LDAP server over a TLS connection. I did need to install the CA cert into the system keychain.
The SwiftUI version, using the exact same code and parameters returns an "Unknown CA" error. It works fine without TLS. Can anyone explain why certificate validation is different for a GUI app?
We have a requirement to create a production quality application that also acts as HTTPS server for certain communication.
The preference is for the server to support HTTP/1.1, HTTP/2 and HTTP/3 communication asynchronously, though not mandatory to support all the HTTP versions. Wanted to get the guidance, on which stack should be used, that is most reliable and that gives the maximum long term compatibility, sustainability and reliability.
What is the recommended 'in-built' or 'available by default' stack on Apple Platform ?
For HTTPS on HTTP/1.1 with synchronous mode operations ?
For HTTPS on HTTP/1.1 with asynchronous mode operations ?
For HTTPS on HTTP/2 with synchronous mode operations ?
For HTTPS on HTTP/2 with asynchronous mode operations ?
For HTTPS on HTTP/3 with asynchronous mode operations ?
For HTTPS on HTTP/1.1 + HTTP/2 with synchronous mode operations ?
For HTTPS on HTTP/1.1 + HTTP/2 with asynchronous mode operations ?
For HTTPS on HTTP/1.1 + HTTP/2 + HTTP/3 with asynchronous mode operations ?
What the generally recommended server stack that a typical application uses whether 'in-built' or 'available by default on Apple ' or 'not-available by default on Apple' stack.
From the available stacks , we tried to evaluate the below stacks:
https://opensource.apple.com/projects/swiftnio/ : We understand that while it’s not preinstalled as part of Apple's OSes, it is an official Swift package supported by Apple and can easily be added to your project. At the moment it supports HTTP/1.1 and HTTP/2. The link https://github.com/apple/swift-nio/issues/1730says that HTTP/3 will get added in the future.
Is there any other HTTPS stack (built-in or third-party) that is recommended to the used on Apple's platform ? Our application is expected to be working on macOS, iOS, iPadOS, tvOS and watchOS.
We understand that macOS also includes Apache HTTPD server. As our application is not primarily a Web Server (and also supports other protocols both in client and server mode), it looks integrating HTTPS directly into the application using a lightweight HTTP library with SSL/TLS support is a better option, in place of Apache HTTPD.
From the document we know that swift-nio uses BoringSSL (swift-nio-ssl) which is prepackaged along with the swift-nio library, and it does not use the default Secure Transport. What is the reason being not using Secure Transport ? Now does it become the responsibility of the application using swift-nio to take care of updating BoringSSL with the patches.
Hi Everyone,
I’m working on a communication system for my app using NWConnection with the UDP protocol. The connection is registered to a custom serial dispatch queue. However, I’m trying to understand what the behavior will be in a scenario where the connection is canceled while there are still pending receive operations in progress.
Scenario Overview:
The sender is transmitting n = 100 packets to the receiver, out of which 40 packets have already been sent (i.e., delivered to the Receiver).
The receiver has posted m = 20 pending receive operations, where each receive operation is responsible for handling one packet.
The receiver has already successfully processed x = 10 packets.
At the time of cancellation, the receiver’s buffer still holds m = 20 packets that are pending for processing, and k = 10 pending receive callbacks are in the dispatch queue, waiting to be executed.
At same time when the 10th packet was processed another thread triggers .cancel() on this accepted NWConnection (on the receiver side), I need to understand the impact on the pending receive operations and their associated callbacks.
My Questions:
What happens to the k = 10 pending receive callbacks that are in the dispatch queue waiting to be triggered when the connection is canceled? Will these callbacks complete successfully and process the data? Or, because the connection is canceled, will they complete with failure?
What happens to the remaining pending receive operations that were initiated but have not yet been scheduled in the dispatch queue? For the pending receive operations that were already initiated (i.e., the network stack is waiting to receive the data, but the callback hasn’t been scheduled yet), will they fail immediately when the connection is canceled? Or is there any chance that the framework might still process these receives before the cancellation fully takes effect?
Reproduce:
Download live-caller-id-lookup-example
Add
let url = URL(string: "http://another-macbook.local:80")!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
print(String(data: data, encoding: .utf8)!)
}
task.resume()
anywhere in the code
run PIRService target in xcode
Result: no dialogue, host is unreachable
Works fine when launching same binary from terminal
Hi ,
I want to obtain detailed information about the cellular network. Please guide me on how I can access these values. If there are any partnership programs available for this, I am ready to participate
1. cell identity
2. Lcellid
3. ratType
4. enb
5. snr
6. ARFCN
7. TA
8. cqi
9. signalStrength (RSSI)
10. tac (Tracking area code)
11. BSIC
12. lac id
13. MCC code (Restricted on some devices)
14. MNC code
15. PSC (Primary Scrambling code)
16. Arbitrary Signal Strength (ASU)
17. BER
18. RSSI
19. Signal Quality
I am trying to programmatically block some egress and ingress connections using bsd packet filters. My program writes rules in a file and this file is loaded using an anchor in /etc/pf.conf (main ruleset) . Rules work as intended. But when there is network change like turn on/off wifi , and change in wifi nw the main ruleset is getting flushed and i have to reapply (pfctl -q -f /etc/pf.conf) to get the rules back in place.
Looking for guidance to keep the main ruleset intact irrespective of system changes.
Hi everyone,
I’m developing an app called FindMyNet that allows users to find the best internet provider based on their postal code (CAP). The app is built with Xcode and the macOS simulator. I’ve set up a FastAPI backend that communicates with an Excel database containing internet provider data for each postal code.
Unfortunately, when I try to run the app, I encounter an error that prevents me from retrieving data from the database and displaying the correct provider.
Task <6B5C86B6-181A-4235-AE68-23AAF6645683>.<1> finished with error [1] Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted" UserInfo={_NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <6B5C86B6-181A-4235-AE68-23AAF6645683>.<1>, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=1, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask <6B5C86B6-181A-4235-AE68-23AAF6645683>.<1>" ), _NSURLErrorNWPathKey=satisfied (Path is satisfied), interface: en0[802.11], ipv4, dns, uses wifi}
Problem description:
• The FastAPI backend is running on a Raspberry Pi and communicates with the app via an HTTP request.
• When I enter a postal code, the app should return the best provider for that region, but I only get a 500 error.
• I’ve verified that the FastAPI server is running, but it seems there’s an issue with communication between the app and the server.
Steps taken so far:
• I’ve checked the logs on the FastAPI server, but there are no obvious errors.
• I’ve manually tested the API using Postman, and it works fine, so the issue seems to be app-side.
Support request:
I’d like to understand better what could be causing this error and if anyone has had similar experiences. Any advice on diagnosing the problem or solutions for resolving it would be greatly appreciated.
Thanks in advance for your help!
I'm using NETransparentProxyProvider to intercept udp sockets using the method handleNewUDPFlow. An application may create a UDP socket and set the DONTFRAG using setsockopt method
setsockopt(s, IPPROTO_IP, IP_DONTFRAG, &val, sizeof(val))
In this case, do I have option in this case, to get the connection settings inside the callback
(void)handleNewUDPFlow:(NEAppProxyUDPFlow *)flow initialRemoteEndpoint:(NWEndpoint *)remoteEndpoint;
So in this case, I would be able to create the outgoing socket with the exact same characteristics, after the original app socket got intercepted by my proxy provider ?
I am developing an Xcode app with a job feed, with profile view, with chat eg. I fetch using federatet queries to my microservices thru Apollo Router. Infront of the Apollo Router i Have a Kong that adds a X user ID, that the microservices use for personalized feed and other user info. The info is stored with SwiftData. My thought is that i should add a better way of controlling when i need to fetch. I have a “lastupdateAPI” with different entities (profile, profile picture eg). So when nothing has changed we do not fetch. But rather then using a own API for this, isnt ETag better? Or is it any other recommendations with Xcode Swiftui. Good strategies for not fetching what i already have?
My application advertises service uuid FC66 and 00410b66-2553-48d7-cf18-000000002154 in advertising data, and "loading" as local name in response data in foreground.
But iOS cut local name to "loadi" and add Hashed UUID data 0100000000000000000000000600000000 to response data.
Why iOS add hashed uuid data? Is it because my 128-bit uuid format is wrong?
We want to advertise the complete local name data.
How to avoid this problem?
When setting up a packet tunnel with a profile that has includeAllNetworks set to true, we seemingly cannot send any traffic inside the tunnel using any kind of an API. We've tried using BSD sockets, as we ping a host only reachable within the tunnel to establish whether we have connectivity - this does not work. When using NWConnection from the Network framework and specifying the required interface via virtualInterface from the packet tunnel, the connection state never reaches ready. Our interim solution is to, as ridiculous as it sounds, include a whole userspace networking stack so we can produce valid TCP packets just to send into our own tunnel. We require a TCP connection within our own tunnel to do some configuration during tunnel setup. Is there no better solution?
I'm using the NEHotspotConfigurationManager class, with joinOnce = false, to connect to a Wi-Fi network that lacks internet access (IoT device).
After restarting my iPhone, the first connection to this network disconnects automatically in less than a minute. All subsequent connections remain stable without disconnecting. What could be causing this?