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

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
80
Jul ’25
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
7
3
204
Aug ’25
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
76
Jul ’25
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
315
Jul ’25
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
155
Jul ’25
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
187
Jul ’25
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
60
Jul ’25
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
182
Jul ’25
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
127
Jun ’25
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
101
Jun ’25
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
93
Jun ’25
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
74
Jun ’25
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
66
Jun ’25
processInfo.hostName requires 'local network' permission on iOS
Either processInfo.hostName should return the same info as UIDevice.name ("iPhone") or it should require the same entitlement that UIDevice.name does to return the actual result. If processInfo.hostName is intended to return the local Bonjour name, why does it need 'local network' permission? Why isn't the 'local network' permission documented for processInfo.hostName as this is hard to track down? Tested on iOS 18.5
2
0
86
Jun ’25
urlSession(_:dataTask:didReceive:) not called when using completion handler-based dataTask(w
Description: I'm noticing that when using the completion handler variant of URLSession.dataTask(with:), the delegate method urlSession(_:dataTask:didReceive:) is not called—even though a delegate is set when creating the session. Here's a minimal reproducible example: ✅ Case where delegate method is called: class CustomSessionDelegate: NSObject, URLSessionDataDelegate { func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { print("✅ Delegate method called: Data received") } } let delegate = CustomSessionDelegate() let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil) let request = URLRequest(url: URL(string: "https://httpbin.org/get")!) let task = session.dataTask(with: request) // ✅ No completion handler task.resume() In this case, the delegate method didReceive is called as expected. ❌ Case where delegate method is NOT called: class CustomSessionDelegate: NSObject, URLSessionDataDelegate { func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { print("❌ Delegate method NOT called") } } let delegate = CustomSessionDelegate() let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil) let request = URLRequest(url: URL(string: "https://httpbin.org/get")!) let task = session.dataTask(with: request) { data, response, error in print("Completion handler called") } task.resume() Here, the completion handler is executed, but the delegate method didReceive is never called. Notes: I’ve verified this behavior on iOS 16, 17, and 18. Other delegate methods such as urlSession(_:task:didFinishCollecting:) do get called with the completion handler API. This happens regardless of whether swizzling or instrumentation is involved — the issue is reproducible even with direct method implementations. Questions: Is this the expected behavior (i.e., delegate methods like didReceive are skipped when a completion handler is used)? If yes, is there any official documentation that explains this? Is there a recommended way to ensure delegate methods are invoked, even when using completion handler APIs? Thanks in advance!
2
0
47
Jun ’25