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

201 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Networking Resources
General: DevForums subtopic: App & System Services > Networking 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 TN3179 Understanding local network privacy Adapt to changing network conditions tech talk Extra-ordinary Networking DevForums post 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. Building a custom peer-to-peer protocol sample code (aka TicTacToe) Implementing netcat with Network Framework sample code (aka nwcat) Configuring a Wi-Fi accessory to join a network sample code Moving from Multipeer Connectivity to Network Framework DevForums post Network Extension (including Wi-Fi on iOS): See Network Extension Resources Wi-Fi Fundamentals TN3111 iOS Wi-Fi API overview Wi-Fi Aware framework documentation 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 What’s new for enterprise in iOS 18 support article — This discusses new key usage requirements. 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 WirelessInsights framework documentation iOS Network Signal Strength Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
0
0
3.2k
1w
Accessing security scoped URLs without calling url.startAccessingSecurityScopedResource
I have discovered a gap in my understanding of user selected URLs in iOS, and I would be grateful if someone can put me right please. My understanding is that a URL selected by a user can be accessed by calling url.startAccessingSecurityScopedResource() call. Subsequently a call to stopAccessingSecurityScopedResource() is made to avoid sandbox memory leaks. Furthermore, the URL can be saved as a bookmark and reconstituted when the app is run again to avoid re-asking permission from the user. So far so good. However, I have discovered that a URL retrieved from a bookmark can be accessed without the call to url.startAccessingSecurityScopedResource(). This seems contrary to what the documentation says here So my question is (assuming this is not a bug) why not save and retrieve the URL immediately in order to avoid having to make any additional calls to url.startAccessingSecurityScopedResource? Bill Aylward You can copy and paste the code below into a new iOS project to illustrate this. Having chosen a folder, the 'Summarise folder without permission' button fails as expected, but once the 'Retrieve URL from bookmark' has been pressed, it works fine. import SwiftUI import UniformTypeIdentifiers struct ContentView: View { @AppStorage("bookmarkData") private var bookmarkData: Data? @State private var showFolderPicker = false @State private var folderUrl: URL? @State private var folderReport: String? var body: some View { VStack(spacing: 20) { Text("Selected folder: \(folderUrl?.lastPathComponent ?? "None")") Text("Contents: \(folderReport ?? "Unknown")") Button("Select folder") { showFolderPicker.toggle() } Button("Deselect folder") { folderUrl = nil folderReport = nil bookmarkData = nil } .disabled(folderUrl == nil) Button("Retrieve URL from bookmark") { retrieveFolderURL() } .disabled(bookmarkData == nil) Button("Summarise folder with permission") { summariseFolderWithPermission(true) } .disabled(folderUrl == nil) Button("Summarise folder without permission") { summariseFolderWithPermission(false) } .disabled(folderUrl == nil) } .padding() .fileImporter( isPresented: $showFolderPicker, allowedContentTypes: [UTType.init("public.folder")!], allowsMultipleSelection: false ) { result in switch result { case .success(let urls): if let selectedUrl = urls.first { print("Processing folder: \(selectedUrl)") processFolderURL(selectedUrl) } case .failure(let error): print("\(error.localizedDescription)") } } .onAppear() { guard folderUrl == nil else { return } retrieveFolderURL() } } func processFolderURL(_ selectedUrl: URL?) { guard selectedUrl != nil else { return } // Create and save a security scoped bookmark in AppStorage do { guard selectedUrl!.startAccessingSecurityScopedResource() else { print("Unable to access \(selectedUrl!)"); return } // Save bookmark bookmarkData = try selectedUrl!.bookmarkData(options: .minimalBookmark, includingResourceValuesForKeys: nil, relativeTo: nil) selectedUrl!.stopAccessingSecurityScopedResource() } catch { print("Unable to save security scoped bookmark") } folderUrl = selectedUrl! } func retrieveFolderURL() { guard let bookmarkData = bookmarkData else { print("No bookmark data available") return } do { var isStale = false let url = try URL( resolvingBookmarkData: bookmarkData, options: .withoutUI, relativeTo: nil, bookmarkDataIsStale: &isStale ) folderUrl = url } catch { print("Error accessing URL: \(error.localizedDescription)") } } func summariseFolderWithPermission(_ permission: Bool) { folderReport = nil print(String(describing: folderUrl)) guard folderUrl != nil else { return } if permission { print("Result of access requrest is \(folderUrl!.startAccessingSecurityScopedResource())") } do { let contents = try FileManager.default.contentsOfDirectory(atPath: folderUrl!.path) folderReport = "\(contents.count) files, the first is: \(contents.first!)" } catch { print(error.localizedDescription) } if permission { folderUrl!.stopAccessingSecurityScopedResource() } } }
7
0
175
2h
Share extension with App Group: UserDefaults don't get persisted on iOS
I have a multiplatform app for Mac and iOS, for which I am implementing a share extension. This share extension has to share settings with the app itself on both platforms. I am currently trying to achieve this by adding all targets to the same App Group and using UserDefaults with the App Group as suiteName. The app consists of three targets: A multiplatform SwiftUI app, an iOS Share Extension, and a macOS Share Extension,. Settings get persisted correctly on Mac and on the iOS 26 simulator. However, on a real iOS 26 beta 3 device, the Share Extension is unable to load UserDefaults (loading anything with the App Group as a suite name returns nil). What could cause this behavior? The following log entries are generated from the Share Extension on the iOS device, but not on the iOS simulator: Couldn't read values in CFPrefsPlistSource<0x1030d3c80> (Domain: MY_APP_GROUP, User: kCFPreferencesAnyUser, ByHost: Yes, Container: (null), Contents Need Refresh: Yes): Using kCFPreferencesAnyUser with a container is only allowed for System Containers, detaching from cfprefsd 59638328 Plugin query method called (501) Invalidation handler invoked, clearing connection (501) personaAttributesForPersonaType for type:0 failed with error Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.mobile.usermanagerd.xpc was invalidated from this process." UserInfo={NSDebugDescription=The connection to service named com.apple.mobile.usermanagerd.xpc was invalidated from this process.} LaunchServices: store (null) or url (null) was nil: Error Domain=NSOSStatusErrorDomain Code=-54 "process may not map database" UserInfo={_LSLine=72, _LSFunction=_LSServer_GetServerStoreForConnectionWithCompletionHandler, _LSFile=LSDReadService.mm, NSDebugDescription=process may not map database} Attempt to map database failed: permission was denied. This attempt will not be retried. Failed to initialize client context with error Error Domain=NSOSStatusErrorDomain Code=-54 "process may not map database" UserInfo={_LSLine=72, _LSFunction=_LSServer_GetServerStoreForConnectionWithCompletionHandler, _LSFile=LSDReadService.mm, NSDebugDescription=process may not map database} [C:1-3] Error received: Invalidated by remote connection.
1
0
52
2d
Disable URLSession auto retry policy
We are developing an iOS application that is interacting with HTTP APIs that requires us to put a unique UUID (a nonce) as an header on every request (obviously there's more than that, but that's irrilevant to the question here). If the same nonce is sent on two subsequent requests the server returns a 412 error. We should avoid generating this kind of errors as, if repeated, they may be flagged as a malicious activity by the HTTP APIs. We are using URLSession.shared.dataTaskPublisher(for: request) to call the HTTP APIs with request being generated with the unique nonce as an header. On our field tests we are seeing a few cases of the same HTTP request (same nonce) being repeated a few seconds on after the other. Our code has some retry logic only on 401 errors, but that involves a token refresh, and this is not what we are seeing from logs. We were able to replicate this behaviour on our own device using Network Link Conditioner with very bad performance, with XCode's Network inspector attached we can be certain that two HTTP requests with identical headers are actually made automatically, the first request has an "End Reason" of "Retry", the second is "Success" with Status 412. Our questions are: can we disable this behaviour? can we provide a new request for the retry (so that we can update headers)? Thanks, Francesco
4
3
115
2d
FileManager.copyItem(atPath:toPath:) not working since iOS / iPad OS 18.4
Hi there, I have discovered that the behavior of file copying has changed starting from iOS 18.4. When using FileManager.copyItem(atPath:toPath:) to copy a directory specified as an argument, whether or not there is a trailing slash ('/') affects whether the copy process works correctly. The same process operates as expected in the iOS 18.3.1 Simulator. Is this the correct behavior, or could it be a bug? The application's build environment is Xcode 16.2. Below is an example of the code. In practice, the file copying is performed within the application's folder. // Both iOS 18.3.1 and iOS 18.4 successfully complete the copy process. FileManager.default.copyItem(atPath: "/path/from/dirA", toPath: "/path/to/dirB") FileManager.default.copyItem(atPath: "/path/from/dirA/", toPath: "/path/to/dirB/") // iOS 18.3.1 successfully complete the copy process, but iOS 18.4 fails. FileManager.default.copyItem(atPath: "/path/from/dirA/", toPath: "/path/to/dirB") I hope this helps Apple engineers and other developers experiencing the same issue. Feedback or additional insights would be appreciated.
1
0
54
1w
Swapping the `objectAtIndex:` method of `__NSArrayM` using `method_exchangeImplementations` will lead to continuous memory growth.
After swapping the -objectAtIndex: method using method_exchangeImplementations, it will cause continuous memory growth. Connect the iPhone and run the provided project. Continuously tap the iPhone screen. Observe Memory; it will keep growing. Sample code
2
0
283
1w
FileManager.removeItem(atPath:) fails with "You don't have permission to access the file" error when trying to remove non-empty directory on NAS
A user of my app reported that when trying to remove a file it always fails with the error "file couldn't be removed because you don't have permission to access it (Cocoa Error Domain 513)". After some testing, we found out that it's caused by trying to delete non-empty directories. I'm using FileManager.removeItem(atPath:) which has worked fine for many years, but it seems that with their particular NAS, it doesn't work. I could work around this by checking if the file is a directory, and if it is, enumerating the directory and remove each contained file before removing the directory itself. But shouldn't this already be taken care of? In the source code of FileManager I see that for Darwin platforms it calls removefile(pathPtr, state, removefile_flags_t(REMOVEFILE_RECURSIVE)) so it seems that it should already work. Is the REMOVEFILE_RECURSIVE flag perhaps ignored by the device? But then, is the misleading "you don't have permission to access the file" error thrown by the device or by macOS? For the FileManager source code, see https://github.com/swiftlang/swift-foundation/blob/1d5d70997410fc8b7700c8648b10d6fc28194202/Sources/FoundationEssentials/FileManager/FileOperations.swift#L444
8
0
124
2d
FileManager.contentsEqual(atPath:andPath:) very slow
Until now I was using FileManager.contentsEqual(atPath:andPath:) to compare file contents in my App Store app, but then a user reported that this operation is way slower than just copying the files (which I made faster a while ago, as explained in Making filecopy faster by changing block size). I thought that maybe the FileManager implementation reads the two files with a small block size, so I implemented a custom comparison with the same block size I use for filecopy (as explained in the linked post), and it runs much faster. When using the code for testing repeatedly also found on that other post, this new implementation is about the same speed as FileManager for 1KB files, but runs 10-20x faster for 1MB files or bigger. Feel free to comment on my implementation below. extension FileManager { func fastContentsEqual(atPath path1: String, andPath path2: String, progress: (_ delta: Int) -> Bool) -> Bool { do { let bufferSize = 16_777_216 let sourceDescriptor = open(path1, O_RDONLY | O_NOFOLLOW, 0) if sourceDescriptor < 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) } let sourceFile = FileHandle(fileDescriptor: sourceDescriptor) let destinationDescriptor = open(path2, O_RDONLY | O_NOFOLLOW, 0) if destinationDescriptor < 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) } let destinationFile = FileHandle(fileDescriptor: destinationDescriptor) var equal = true while autoreleasepool(invoking: { let sourceData = sourceFile.readData(ofLength: bufferSize) let destinationData = destinationFile.readData(ofLength: bufferSize) equal = sourceData == destinationData return sourceData.count > 0 && progress(sourceData.count) && equal }) { } if close(sourceDescriptor) < 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) } if close(destinationDescriptor) < 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) } return equal } catch { return contentsEqual(atPath: path1, andPath: path2) // use this as a fallback for unsupported files (like symbolic links) } } }
2
0
172
1w
Keyboard becomes unresponsive after backgrounding app while iCloud Keychain “Save Password?” sheet is visible
Product & Version: iOS 17.5.1 (21F90) – reproducible since iOS 13 Test devices: iPhone 14 Pro, iPhone 15, iPad (10th gen) Category: UIKit → Text Input / Keyboard Summary: If the system “Save Password?” prompt (shown by iCloud Keychain after a successful login) is onscreen and the user sends the app to background (Home gesture / App Switcher), the prompt is automatically dismissed. When the app returns to foreground, the keyboard does not appear, and text input is impossible in the entire app until it is force-quit. Steps to Reproduce: Run any app from AppStore that shows "Save Password" alert. Enter any credentials and tap Login, iOS shows the system “Save Password?” alert. Without interacting with the alert, swipe up to the Home screen (or open the App Switcher). Reactivate the app. Tap the text field in the app.
2
0
46
2w
Memory Zeroing Issue After iOS 18 Update
After iOS 18, some new categories of crash exceptions appeared online, such as those related to the sqlite pcache1 module, those related to the photo album PHAsset, those related to various objc_release crashes, etc. These crash scenarios and stacks are all different, but they all share a common feature, that is, they all crash due to accessing NULL or NULL addresses with a certain offset. According to the analysis, the direct cause is that a certain pointer, which previously pointed to valid memory content, has now become pointing to 0 incorrectly and mysteriously. We tried various methods to eliminate issues such as multi-threading problems. To determine the cause of the problem, we have a simulated malloc guard detection in production. The principle is very simple: Create some private NSString objects with random lengths, but ensure that they exceed the size of one memory physical page. Set the first page of memory for these objects to read-only (aligning the object address with the memory page). After a random period of time (3s - 10s), reset the memory of these objects to read/write and immediately release these objects. Then repeat the operation starting from step 1. In this way, if an abnormal write operation is performed on the memory of these objects, it will trigger a read-only exception crash and report the exception stack. Surprisingly, after the malloc guard detection was implemented, some crashes occurred online. However, the crashes were not caused by any abnormal rewriting of read-only memory. Instead, they occurred when the NSString objects were released as mentioned earlier, and the pointers pointed to contents of 0. Therefore, we have added object memory content printing after object generation, before and after setting to read-only, and before and after reverting to read-write. The result was once again unexpected. The log showed that the isa pointer of the object became 0 after setting to read-only and before re-setting to read-write. So why did it become 0 during read-only mode, but no crash occurred due to the read-only status? We have revised the plan again. We have added a test group, in which after the object is created, we will mlock the memory of the object, and then munlock it again before the object is released. As a result, the test analysis showed that the test group did not experience a crash, while the crashes occurred entirely in the control group. In this way, we can prove that the problem occurs at the system level and is related to the virtual memory function of the operating system. It is possible that inactive memory pages are compressed and then cleared to zero, and subsequent decompression fails. This results in the accidental zeroing out of the memory data. As mentioned at the beginning, althougth this issue is a very rare occurrence, but it exists in various scenarios. definitely It appeared after iOS 18. We hope that the authorities will pay attention to this issue and fix it in future versions.
4
0
148
2w
Access resource in swift package from xcframework
I have an iOS app that includes a local Swift package. This Swift package contains some .plist files added as resources. The package also depends on an XCFramework. I want to read these .plist files from within the XCFramework. What I’d like to know is: Is this a common or recommended approach—having resources in a Swift package and accessing them from an XCFramework? Previously, I had the .plist files added directly to the main app target, and accessing them from the XCFramework felt straightforward. With the new setup, I’m trying to determine whether this method (placing resources in a Swift package and accessing them from an XCFramework) is considered good practice. For context: I am currently able to read the .plist files from the XCFramework by passing Bundle.module through one of the APIs exposed by the XCFramework.
3
1
111
3w
NSuserdefault issue after restart my iphone
hi,guys.There's a issue about my app about NSuserdefault. Everything is arlright if i stay in the app, once i close my app, and restart it.Datas from nsuserdefault is gone(nil). i tried to add and delete synchronize method , but its not working. But this situation only happens in ios 18.(at least ios12 and ios16 is alright).
3
0
87
3w
iOS 26 Developer Beta 2
I’m running iOS 26 Developer Beta 2 on my iPhone 13 Pro and it’s not letting me call anyone on it you should fi that with the next beta of iOS 26 and every one of the iOS 26 beta updates after that even when you release the up iOS 26 later this fall
0
0
70
3w
JSONDecoder enum-keyed dictionary bug
Hello everyone, I think I've discovered a bug in JSONDecoder and I'd like to get a quick sanity-check on this, as well as hopefully some ideas to work around the issue. When attempting to decode a Decodable struct from JSON using JSONDecoder, the decoder throws an error when it encounters a dictionary that is keyed by an enum and somehow seems to think that the enum is an Array<Any>. Here's a minimal reproducible example: let jsonString = """ { "variations": { "plural": "tests", "singular": "test" } } """ struct Json: Codable { let variations: [VariationKind: String] } enum VariationKind: String, Codable, Hashable { case plural = "plural" case singular = "singular" } and then the actual decoding: let json = try JSONDecoder().decode( Json.self, from: jsonString.data(using: .utf8)! ) print(json) The expected result would of course be the following: Json( variations: [ VariationKind.plural: "tests", VariationKind.singular: "test" ] ) But the actual result is an error: Swift.DecodingError.typeMismatch( Swift.Array<Any>, Swift.DecodingError.Context( codingPath: [ CodingKeys(stringValue: "variations", intValue: nil) ], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil ) ) So basically, the JSONDecoder tries to decode Swift.Array<Any> but encounters a dictionary (duh), and I have no idea why this is happening. There are literally no arrays anywhere, neither in the actual JSON string, nor in any of the Codable structs. Curiously, if I change the dictionary from [VariationKind: String] to [String: String], everything works perfectly. So something about the enum seems to cause confusion in JSONDecoder. I've tried to fix this by implementing Decodable myself for VariationKind and using a singleValueContainer, but that causes exactly the same error. Am I crazy, or is that a bug?
1
0
60
3w
Could not delete cookies on IOS18
Hello, I have encountered an issue with an iPhone 15PM with iOS 18.5. The NSHTTPCookieStorage failed to clear cookies, after clearing them, I was still able to retrieve them. However, on the same system NSHTTPCookie *cookie; NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; for (cookie in [storage cookies]) { [storage deleteCookie:cookie]; } NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[[self url] absoluteURL]]; // still able to get cookies,why???
1
0
48
3w