Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

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

Effect of app nap of Timer
I'm developing a macOS application that tracks the duration of a user's session using a timer, which is displayed both in the main window and in an menu bar extra view. I have a couple of questions regarding the timer's behavior: What happens to the timer if the user closes the application's window (causing the app to become inactive) but does not fully quit it? Does the timer continue to run, pause, or behave in some other way? Will the app nap feature stop the timer when app is in-active state? When the application is inactive and the system is either in sleep mode or locked, does the timer’s tolerance get affected? In other words, will the timer fire with any additional delay compared to its scheduled time under these conditions?
1
0
46
Mar ’25
NSString initWithFormat crash on ios18
var format = "%7B%22sign%22%3Anull%2C%22company%22%3A%22%E5%85%84%E5%BC%9F%E6%B5%B7%E6%B4%8B%E7%A7%91%E6%8A%80%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22%2C%22businessNo%22%3Anull%2C%22scene%22%3Anull%2C%22interviewCode%22%3A%22767676%22%7D" let message = withVaList([]) { args in let msg = NSString(format: format, arguments: args) print(msg) }
6
0
96
Mar ’25
Issue with storing NSCoding object in userdefaults
Hi all. I need to save an array of strings in userdefaults. I am using NSKeyedArchiver.archivedData(withRootObject: rootObject, requiringSecureCoding: false) to convert array of string to data and then save it in userdefaults. Inorder to retrieve the data back, I am using let data = self.userDefaults.data(forKey: "key")! let unarchiver = try NSKeyedUnarchiver(forReadingFrom: data) unarchiver.requiresSecureCoding = false let array = unarchiver.decodeObject(forKey: NSKeyedArchiveRootObjectKey) as? NSObject This was working perfectly till iOS 18. From iOS 18 in couple of devices, we are getting empty string array while we retrieve the value back from userdefaults. We observed this in an iPhone 12 pro and iPhone 15 running on iOS 18. iPhone 12 pro is facing this issue almost once everyday. In iPhone 15 this happens once in 2-3 days. Tried printing raw data directly from userdefaults. And I can see some data available. But when we convert that back to array of string, I am getting empty. Tried adding logs in catch block. But couldn't get any. What might be the cause of this issue?
1
0
97
Mar ’25
Local Network Permission Issue
We're experiencing an issue with Local Network Permission. When trying to connect to a socket, the Local Network Permission alert pops up. To trigger the permission request at the start of the app, we used the following code to ask for permission and receive a callback on whether it's granted. However, this approach doesn't always trigger the permission alert, or it gets automatically dismissed after 30 seconds, only to reappear later. What could be causing this inconsistent behavior? func checkLocalNetworkPermission(_ completed: Optional<(Bool) -> Void> = .none) { DispatchQueue.global(qos: .userInitiated).async { let hostName = ProcessInfo.processInfo.hostName let isGranted = hostName.contains(".local") if let completed { DispatchQueue.main.async { completed(isGranted) } } } }
1
0
164
Mar ’25
This bundle is invalid - Your archive contains paths that are not allowed:
Hi there, I uploaded an update bundle for the posted app, but I got a rejection message. ITMS-90048: This bundle is invalid - Your archive contains paths that are not allowed: [._Symbols] The XCode version I'm using is 16.2, and I've been trying to find a route using Run Script and Finder, but I don't know what the hell it is about. Does anybody know what could cause this issue? Any help would be appreciated. Thanks.
19
6
3.6k
Apr ’25
ios18 crash reason: '*** -[__NSArrayM insertObjects:count:atIndex:]: attempt to insert nil object from objects[126976]'
Recently, my application has been receiving a lot of crashes every day, appearing on the iOS18 system. I can't find where the problem is and how can I solve it? Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] Date/Time: 2025-03-10 14:55:49.541 +0800 OS Version: iOS 18.3.1 (22D72) Report Version: 104 Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x00000000 at 0x0000000000000000 Triggered by Thread: 1 Application Specific Information: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObjects:count:atIndex:]: attempt to insert nil object from objects[126976]' Thread 0: 0 libsystem_kernel.dylib 0x00000001e95c4788 mach_msg2_trap + 8 1 libsystem_kernel.dylib 0x00000001e95c7e98 mach_msg2_internal + 80 2 libsystem_kernel.dylib 0x00000001e95c7db0 mach_msg_overwrite + 424 3 libsystem_kernel.dylib 0x00000001e95c7bfc mach_msg + 24 4 CoreFoundation 0x0000000197ee3804 0x197e6d000 + 485380 5 CoreFoundation 0x0000000197ee2eb0 0x197e6d000 + 482992 6 CoreFoundation 0x0000000197f35284 CFRunLoopRunSpecific + 588 7 GraphicsServices 0x00000001e51a14c0 GSEventRunModal + 164 8 UIKitCore 0x000000019aa7e674 0x19a690000 + 4122228 9 UIKitCore 0x000000019a6a4e88 UIApplicationMain + 340 10 MyApp 0x0000000102dbfd70 main + 104 11 (null) 0x00000001be18dde8 0x0 + 7484268008 Thread 1 name: com.apple.uikit.xpc-service Thread 1 Crashed: 0 CoreFoundation 0x0000000197e9a5fc 0x197e6d000 + 185852 1 libobjc.A.dylib 0x0000000195415244 objc_exception_throw + 88 2 CoreFoundation 0x0000000197ed46bc 0x197e6d000 + 423612 3 CoreFoundation 0x0000000197ed37b0 0x197e6d000 + 419760 4 CoreFoundation 0x0000000197e7f5f8 0x197e6d000 + 75256 5 MyApp 0x0000000103e4d4c0 startup_check_root + 12380 6 libdispatch.dylib 0x000000019fc2d248 0x19fc2b000 + 8776 7 libdispatch.dylib 0x000000019fc2efa8 0x19fc2b000 + 16296 8 libdispatch.dylib 0x000000019fc365cc 0x19fc2b000 + 46540 9 libdispatch.dylib 0x000000019fc37124 0x19fc2b000 + 49444 10 libdispatch.dylib 0x000000019fc4238c 0x19fc2b000 + 95116 11 libdispatch.dylib 0x000000019fc41bd8 0x19fc2b000 + 93144 12 libsystem_pthread.dylib 0x0000000222c04680 _pthread_wqthread + 288 13 libsystem_pthread.dylib 0x0000000222c02474 start_wqthread + 8
3
0
303
Mar ’25
Write access with URL.startAccessingSecurityScopedResource
In my App I want to create a new directory structure in a user selected base directory. In the entitlements com.apple.security.files.user-selected.read-write = true is defined. I call URL.startAccessingSecurityScopedResource( ) and get a true value back. When calling FileManager.createDirectory( at: directoryURL, withIntermediateDirectories: true, attributes: nil ) an error is thrown that write access is missing. User has write permissions in that directory. When the user selects a directory I store a bookmark via an @AppStorage variable. After write attempt URL.stopAccessingSecurityScopedResource() is called. I have also implemented a SharedExtension (especially for the Photo app). When user calls the SharedExtension of my app and the app just uses the bookmark stored with @AppStorage and follows the same process as described above no difficulties appear and directories are created as expected. Changing back to the main app, using again the untouched bookmark and execute the exactly same code as in the first attempt everything works fine and as expected. The phenomenon appears on real devices but not on simulator. Any ideas how to solve the issue of having no write access in first attempt?
4
0
256
Mar ’25
json array shows in debugger but can't parse
Hello, I have a json array showing in Xcode debugger (from the line "print(dataString)"): Optional("[{\"id\":\"8e8tfdcssu4u2hn7a71tkveahjhn8xghqcfkwf1bzvtrw5nu0b89w\",\"name\":\"Ameliana\",\"country\":\"France\",\"type\":\"Private\\/Corporate\",\"overallrecsit\":\"Positive\",\"dlastupd\":\"1741351633\",\"doverallrecsit\":\"1546848000\"},{\"id\":\"z69718a1a5z2y5czkwrhr1u37h7h768v05qr3pf1fegh4r4yrt5a68\",\"name\":\"Timberland\",\"country\":\"Switzerland\",\"type\":\"Charter\",\"overallrecsit\":\"Negative\",\"dlastupd\":\"1741351615\",\"doverallrecsit\":\"1740434582\"}, But my JSON decoder is throwing the catch error "Error in JSON parsing" This is the code: super.viewDidLoad() let urlString = "https://www.pilotjobsnetwork.com/service_ios.php" let url = URL(string: urlString) guard url != nil else { return } let session = URLSession.shared let dataTask = session.dataTask(with: url!) { (data, response, error) in var dataString = String(data: data!, encoding: String.Encoding.utf8) print(dataString) if error == nil && data != nil { // Parse JSON let decoder = JSONDecoder() do { let newsFeed = try decoder.decode(NewsFeed.self, from: data!) print(newsFeed) print(error) } catch{ print("Error in JSON parsing") } } } // Make the API Call dataTask.resume() } And this is my Codable file NewsFeed.swift: struct NewsFeed: Codable { var id: String var name: String var country: String var type: String var overallrecsit: String var dlastupd: String var doverallrecsit: String } Please do you know why the parsing may be failing? Is it significant that in the debugging window the JSON is displaying backslashes before the quotation marks? Thank you for any pointers :-)
2
0
305
Mar ’25
Use FormatStyle to print formatted values from a Vector structure
I'm trying to use FormatStyle from Foundation to format numbers when printing a vector structure. See code below. import Foundation struct Vector<T> { var values: [T] subscript(item: Int) -> T { get { values[item] } set { values[item] = newValue } } } extension Vector: CustomStringConvertible { var description: String { var desc = "( " desc += values.map { "\($0)" }.joined(separator: " ") desc += " )" return desc } } extension Vector { func formatted<F: FormatStyle>(_ style: F) -> String where F.FormatInput == T, F.FormatOutput == String { var desc = "( " desc += values.map { style.format($0) }.joined(separator: " ") desc += " )" return desc } } In the example below, the vector contains a mix of integer and float literals. The result is a vector with a type of Vector<Double>. Since the values of the vector are inferred as Double then I expect the print output to display as decimal numbers. However, the .number formatted output seems to ignore the vector type and print the values as a mix of integers and decimals. This is fixed by explicitly providing a format style with a fraction length. So why is the .formatted(.number) method ignoring the vector type T which is Double in this example? let vec = Vector(values: [-2, 5.5, 100, 19, 4, 8.37]) print(vec) print(vec.formatted(.number)) print(vec.formatted(.number.precision(.fractionLength(1...)))) ( -2.0 5.5 100.0 19.0 4.0 8.37 ) // correct output that uses all Double types ( -2 5.5 100 19 4 8.37 ) // wrong output that uses Int and Double types ( -2.0 5.5 100.0 19.0 4.0 8.37 ) // correct output that uses all Double types
2
0
269
Mar ’25
Use native Swift API for HTTP request with auth proxy
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) } } }
2
0
342
Mar ’25
Can we create a bundled non-interactive macOS application which uses CFRunLoop only(instead of using NSApplicationMain to run NSRunLoop)?
I am developing a macOS non-interactive macOS application which does not show any ui. i want to block main thread and do all the work on worker thread . Once done with work in worker thread, want to unblock main thread by exiting event loop to terminate application. Because i dont want to show any UI or use any Foundation/Cocoa functionality, i am thinking of using CFRunLoop to block main thread from exiting until i finish my work in worker thread. When i tried this in a project, I am able to finish work in worker thread after block main thread using CFRunLoop. I also want this application to be a bundled application, which can be launched by double clicking on application bundle . But when i tried it in my xcode project by launching it using double clicking on application bundle, application keeps on toggling/bouncing in the dock menu with a status "Not responding". Although i am able to complete my work in worker thread. import Foundation let runLoop = CFRunLoopGetCurrent() func workerTask() { DispatchQueue.global().async { print("do its work") sleep(5) // do some work print("calling exit event loop") CFRunLoopStop(runLoop) print ("unblocking main thread") } } workerTask () // blocking main thread print ("blocked main thread") CFRunLoopRun() print ("exit") Why i am getting this application bouncing in doc menu behavior ? I tried by using NSApplicationMain instead of CFRunLoop in my project, in that case i didnt get this behavior . Does NSApplicationMain does some extra work before starting NSRunLoop which i am not doing while using CFRunLoop, which is showing this toggling/Bouncing application icon in Dock menu ? or Is this bouncing app icon issue is related to run loop i am using which is CFRunLoop ? Note : If i dont use a bundled application and use a commandline application then i am able to do all steps in worker thread and exit main thread as i wanted after finishing my work . But i need to do all this in application which can be launched using double clicking (bundled applcation). If not by using CFRunLoop, then how can i achive this ? - Create a application which shows no UI and do all work in worker thread while main thread is blocked. Once work is done unblock main thread and exit. And user should be able to launch application using double click the application icon.
3
0
381
Mar ’25
Foundation (?) mangles diacriticals in Greek Extended (U+1F54)
(NOTE: In sum, this is destructive of user data.) The client is a professor of Classics in constant need of properly-rendered glyphs that represent legitimate code points. As an example, the correct spelling might be: εὔτρητος It is spelled and rendered as intended. A file by this name will be correctly spelled by ls in the Terminal. Note that two diacritics are applied to the second letter, an upsilon (ὔ) However, the Finder displays that file as ἐύτρητος and iterating the string reveals that the accents are improperly distributed over the two. This would never be correct. This handicaps digital-humanities researchers from college to postdoctoral work. A Character by Character iteration demonstrates the mangling.: intended (εὔτρητος) displayed (ἐύτρητος) 3B5 (ε) 1F10 (ἐ) GREEK SMALL LETTER EPSILON, GREEK SMALL LETTER EPSILON WITH PSILI 1F54 (ὔ) 3CD (ύ) GREEK SMALL LETTER UPSILON WITH PSILI AND OXIA GREEK SMALL LETTER UPSILON WITH TONOS 3C4 (τ) 3C4 (τ) (back in sync) 3C1 (ρ) 3C1 (ρ) 3B7 (η) 3B7 (η) 3C4 (τ) 3C4 (τ) 3BF (ο) 3BF (ο) 3C2 (ς) 3C2 (ς) I don't want to muddy the waters by guessing where and how the mistake is made, just see for yourself.
1
0
295
Feb ’25
On-Demand Resources Update
Hi, I have a question about On-Demand Resources, I tried to put some bundles into the Initial Install Tags and Download Only On Demand, and I uploaded the build to TestFlight, then I tried to make 2 builds, and the sample is like this: Build A: Initial Install Tags have 100 Tags. Download Only On Demand have 5 Tags. Build B: all contents of Initial Install Tags are the same as in Build A. Download Only On Demand are the same as Build A but I added 5 more tags, so the total is 10 tags, 5 tags that are the same as Build A and 5 new tags. Then I tried to download Build A for the first time which is in TestFlight, and it runs normally, Initial Install Tags are downloaded when the main app is downloaded and Download Only On Demand is downloaded when I request the tag. However, when I tried to update to Build B which is in TestFlight, why are the Initial Install Tags deleted? and why should it be downloaded via request? not when the main app is downloaded? has anyone ever experienced something like this? Thanks!
0
0
191
Feb ’25
Runtime error when trying to read a file
Hello, I'm a newer Xcode developer trying to debug an error I'm getting in my iOS app. I'm using this code to get file content: //inputFile = "here is my file name with no extension" let filepath = Bundle.main.path(forResource: inputFile, ofType: "txt") //filepath = "/Users/username/Library/Developer/CoreSimulator/Devices/[DeviceGUID]/data/Containers/Bundle/Application/[AppGUID]/AppName.app/here is my file name with no extension.txt" let fileContent = try String(contentsOfFile: filepath) That line generates a runtime error: error NSError domain: "NSCocoaErrorDomain" - code: 264 0x0000600000c74d20 Xcode 16.2 on macOS Sequoia 15.1.1 I had this code working... I had to step away from the code for a few months; I updated Xcode and now I'm getting this error. (I could've screwed the code up). I navigated to the directory and the file is there. Anybody have any ideas? Thank you! Hoss
1
0
271
Feb ’25
[MacOS] Accessing underlying pthread or mach thread of NSThread
Is the title possible ? I tried [[thread valueForKey:@"_private"] valueForKey:@"tid"] but the tid was not kvc compliant. private apis are alright because this is just for testing remote process thread creation. I already have a working method but it has hardcoded assembly so you can't do anything else. this question is mainly for Quinn (figured he may know something about this)
2
0
289
Feb ’25
: 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&lt;0x3034e7f80&gt; (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!
8
0
664
Mar ’25
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.
2
0
706
Feb ’25