Foundation

RSS for tag

Access essential data types, collections, and operating-system services to define the base layer of functionality for your app using Foundation.

Posts under Foundation tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Networking Resources
General: TN3151 Choosing the right networking API Networking Overview document — Despite the fact that this is in the archive, this is still really useful. TLS for App Developers DevForums post Choosing a Network Debugging Tool documentation WWDC 2019 Session 712 Advances in Networking, Part 1 — This explains the concept of constrained networking, which is Apple’s preferred solution to questions like How do I check whether I’m on Wi-Fi? TN3135 Low-level networking on watchOS Adapt to changing network conditions tech talk Foundation networking: DevForums tags: Foundation, CFNetwork URL Loading System documentation — NSURLSession, or URLSession in Swift, is the recommended API for HTTP[S] on Apple platforms. Network framework: DevForums tag: Network Network framework documentation — Network framework is the recommended API for TCP, UDP, and QUIC on Apple platforms. Network Extension (including Wi-Fi on iOS): See Network Extension Resources Wi-Fi Fundamentals Wi-Fi on macOS: DevForums tag: Core WLAN Core WLAN framework documentation Wi-Fi Fundamentals Secure networking: DevForums tags: Security Apple Platform Security support document Preventing Insecure Network Connections documentation — This is all about App Transport Security (ATS). Available trusted root certificates for Apple operating systems support article Requirements for trusted certificates in iOS 13 and macOS 10.15 support article About upcoming limits on trusted certificates support article Apple’s Certificate Transparency policy support article Technote 2232 HTTPS Server Trust Evaluation Technote 2326 Creating Certificates for TLS Testing QA1948 HTTPS and Test Servers Miscellaneous: More network-related DevForums tags: 5G, QUIC, Bonjour On FTP DevForums post Using the Multicast Networking Additional Capability DevForums post Investigating Network Latency Problems DevForums post Local Network Privacy FAQ DevForums post Extra-ordinary Networking DevForums post Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
0
0
2.8k
Feb ’24
: Issue with App Group Preferences in iOS Message Extension
I’m encountering an issue while reading/writing shared preferences using UserDefaults with an App Group in my iOS Message Extension. The following error appears in the console: `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 have correctly enabled the App Group in both my containing app and the Message Extension, and I am using UserDefaults(suiteName:) to access shared preferences. However, I keep getting this error when trying to read/write values. Has anyone encountered this before? How can I properly configure my app group preferences to avoid this issue? Any help would be greatly appreciated!
0
0
41
10h
macOS Sequoia: Shared UserDefaults don't work (the app-group is set as per macOS 15 Sequoia requirements)
I use shared UserDefaults in my Swift FileProvider extension app suite. I share data between the containing app and the extension via User Defaults initialized with init(suiteName:). Everything was working fine before macOS 15 (Sequoia). I know that Sequoia changed the way the app group should be configured. My app group is know set to "$(TeamIdentifierPrefix)com.my-company.my-app". But the containing (UI) app and the Extension read and write from and to different plist locations although the same app-group is specified for both targets in XCode. The containing app reads and writes to "~/Library/Preferences/$(TeamIdentifierPrefix)com.my-company.my-app.plist" The Extension reads and writes to "~/Library/Containers/com.my-company.my-app.provider/Data/Library/Preferences$(TeamIdentifierPrefix)com.my-company.my-app.plist" Both of these locations seem completely illogical for shared UserDefaults. I checked the value returned by FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "$(TeamIdentifierPrefix)com.my-company.my-app" in both the containing app and the Extension and the value in both of them is the same but has nothing to do with the actual paths where the data is stored as provided above. (The value is as expected - "~/Library/Group Containers/$(TeamIdentifierPrefix)com.my-company.my-app/" P.S. Of course, $(TeamIdentifierPrefix), my-company and my-app here are placeholders for my actual values.
1
0
192
22h
Dateformatter returns date in incorrect format
I have configured DateFormatter in the following way: let df = DateFormatter() df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" df.locale = .init(identifier: "en") df.timeZone = .init(secondsFromGMT: 0) in some user devices instead of ISO8601 style it returns date like 09/25/2024 12:00:34 Tried to change date format from settings, changed calendar and I think that checked everything that can cause the problem, but nothing helped to reproduce this issue, but actually this issue exists and consumers complain about not working date picker. Is there any information what can cause such problem? May be there is some bug in iOS itself?
1
0
149
5d
Date that is not linked to TimeZone
Hello, I'm creating an app that stores multiple Date objects: the users selects a date and a time and receives a notification at this time precisely. The problem that happens is after saving a Date, if the device's timezone changes, the Date also changes - and that is not what's I'm expecting (just want the original time as is without depending on timezone). I have inspected the TimeZone properties when I'm building the Date from DateComponents but nothing has worked. Thank you for your answer.
1
0
179
6d
Add Authorization header to WKWebView.
How can i add Authorization header to a wkwebview. I checked https://developer.apple.com/documentation/foundation/nsurlrequest#1776617 which says Authorization header is a reserved http header and shouldn’t be set. I want to set it when requesting a url to the server which will be used for verification. How can i do that?
0
0
160
1w
URLSession works for request but not NWConnection
I am trying to convert a simple URLSession request in Swift to using NWConnection. This is because I want to make the request using a Proxy that requires Authentication. I posted this SO Question about using a proxy with URLSession. Unfortunately no one answered it but I found a fix by using NWConnection instead. Working Request func updateOrderStatus(completion: @escaping (Bool) -> 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) } } }
1
0
145
6d
Possible to allow x code builds to run background processes for over 3 minutes
I have an app that I'm using for my own purposes and is not in the app store. I would like to run an http server in the background for more than the allotted 3 minutes to allow persistent communications with a connected Bluetooth device. The Bluetooth device would poll the service at intervals. Is this possible to do? This app does not need app store approval since it's only for personal use.
2
0
121
1w
Hash Collision in Data type
I notice that Swift Data type's hashValue collision when first 80 byte of data and data length are same because of the Implementation only use first 80 bytes to compute the hash. https://web.archive.org/web/20120605052030/https://opensource.apple.com/source/CF/CF-635.21/CFData.c also, even if hash collision on the situation like this, I can check data is really equal or not by == does there any reason for this implementation(only use 80 byte of data to make hashValue)? test code is under below let dataArray: [UInt8] = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] var dataArray1: [UInt8] = dataArray var dataArray2: [UInt8] = dataArray dataArray1.append(contentsOf: [0x00, 0x00, 0x00, 0x00]) dataArray2.append(contentsOf: [0xff, 0xff, 0xff, 0xff]) let data1 = Data(dataArray1) let data2 = Data(dataArray2) // Only last 4 byte differs print(data1.hashValue) print(data2.hashValue) print(data1.hashValue == data2.hashValue) // true print(data1 == data2) // false
1
0
250
1w
Use proxy for http request from iOS device
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, "") } } }
2
0
204
6d
mac mini m4 The camera is not working
I bought a Mac mini M4 and when I used it to sign up for a developer account, I was always encountered, it needed me to take a photo, but I didn't have a camera, so I used the iriun software to connect my phone to take a photo, it works fine in FaceTime, but when I take a photo in the Apple Developer app, the round photo frame is shown black. How can I make the camera work and if I buy a third-party camera?
1
0
175
1w