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

Sendability for Stream, InputStream, etc.
I have a project with some legacy networking code that uses the Stream (formerly NSStream) family of classes, including Stream, InputStream, OutputStream, and StreamDelegate. None of these are sendable, so I get a lot of warnings when implementing delegate methods in a @MainActor class. These classes seem like they could be sendable. Is this something that will happen soon? Is it a bug I should report? The networking code that uses these classes runs great, and hasn't needed changes for years, so my current solution is to just mark these unchecked: extension Stream: @unchecked Sendable { } extension InputStream: @unchecked Sendable { } extension OutputStream: @unchecked Sendable { } This makes the compiler happy, but makes me feel kind of bad. Is there something else I could do?
1
0
216
Jun ’24
NSURL CFNetwork Crashed in iOS18 Beta
When I initiate the following request in the app delegate, it is good in iOS 17, but it will crash in iOS 18. The code is as below: NSString *url = @"https://www.baidu.com"; NSString * restr = [NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSUTF8StringEncoding error:nil]; The stack is as below: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSFileManager createDirectoryAtURL:withIntermediateDirectories:attributes:error:]: URL is nil' *** First throw call stack: ( 0 CoreFoundation 0x00007ff8004c14d5 __exceptionPreprocess + 242 1 libobjc.A.dylib 0x00007ff800084116 objc_exception_throw + 62 2 Foundation 0x00007ff800f00861 -[NSFileManager contentsOfDirectoryAtPath:error:] + 0 3 CFNetwork 0x00007ff804c66bfd -[_NSHTTPAlternativeServicesStorage _onqueue_initializeDatabaseIfNotEmpty:] + 488 4 CFNetwork 0x00007ff804c69350 __66-[_NSHTTPAlternativeServicesStorage HTTPServiceEntriesWithFilter:]_block_invoke + 48 5 libdispatch.dylib 0x0000000115349f32 _dispatch_client_callout + 8 6 libdispatch.dylib 0x000000011535ad86 _dispatch_lane_barrier_sync_invoke_and_complete + 133 7 CFNetwork 0x00007ff804c65bf7 -[_NSHTTPAlternativeServicesStorage HTTPServiceEntriesWithFilter:] + 211 8 CFNetwork 0x00007ff804cd5ccc _ZN11TubeManager34_onqueue_enqueueRequestForProtocolEP25MetaConnectionCacheClientPK18HTTPRequestMessage21MetaConnectionOptionsP16BaseAwaitingTube + 264 9 CFNetwork 0x00007ff804bf8b0c ___ZN12XTubeManager25enqueueRequestForProtocolEP25MetaConnectionCacheClientPK18HTTPRequestMessage21MetaConnectionOptionsPK17CoreSchedulingSet_block_invoke + 328 10 CFNetwork 0x00007ff804bf8832 _ZN12XTubeManager15withTubeManagerEPK17CoreSchedulingSetU13block_pointerFvP15GlueTubeManagerE + 516 11 CFNetwork 0x00007ff804d27823 _ZN12HTTPProtocol81asynchronouslyCreateAndOpenStream_WithMessage_AfterCookiesAndAuthenticatorHeadersEP15__CFHTTPMessage + 6077 12 CFNetwork 0x00007ff804d25ea3 _ZN12HTTPProtocol48asynchronouslyAddAuthenticatorHeadersAndContinueEP15__CFHTTPMessage + 103 13 CFNetwork 0x00007ff804d295b3 ___ZN12HTTPProtocol35asynchronouslyAddCookiesAndContinueEP15__CFHTTPMessage_block_invoke_3 + 26 14 CFNetwork 0x00007ff804e0fdb7 ___ZNK18QCoreSchedulingSet12performAsyncEU13block_pointerFvvE_block_invoke + 41 15 libclang_rt.asan_iossim_dynamic.dyl 0x0000000115d0fa4c __wrap_dispatch_async_block_invoke + 204 16 libdispatch.dylib 0x0000000115348ba9 _dispatch_call_block_and_release + 12 17 libdispatch.dylib 0x0000000115349f32 _dispatch_client_callout + 8 18 libdispatch.dylib 0x0000000115351e3b _dispatch_lane_serial_drain + 1078 19 libdispatch.dylib 0x0000000115352bbc _dispatch_lane_invoke + 448 20 libdispatch.dylib 0x0000000115353be7 _dispatch_workloop_invoke + 876 21 libdispatch.dylib 0x000000011535fcc6 _dispatch_root_queue_drain_deferred_wlh + 318 22 libdispatch.dylib 0x000000011535f205 _dispatch_workloop_worker_thread + 853 23 libsystem_pthread.dylib 0x000000011521db84 _pthread_wqthread + 327 24 libsystem_pthread.dylib 0x000000011521cacf start_wqthread + 15 ) libc++abi: terminating due to uncaught exception of type NSException
2
0
226
Jun ’24
JSON Encoder Crashing
Hi For some of the user the JSON Encoder is giving crash while converting array of Models into the dictionary its not reproducible at our end. Below is the stack trace of the issue 2024-06-14_21-18-38.4054_-0500-90aad9908d4fb2c7b8e49ce4b3025fab79674e31.crash Please help with above crash how can we reproduce and what should be the solution for this. Thanks
1
0
213
Jun ’24
The DateFormatter is returning wrong date format 2024-04-23T7:52:49.352 AMZ, 2024-05-23T11:16:24.706 a.m.Z
import Foundation let formatter = DateFormatter() let displayLocalFormat = true or false let timeZone = UTC let dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" let currentDate = Date() formatter.locale = displayLocalFormat ? Locale.current : Locale(identifier: "en_US_POSIX") formatter.dateFormat = dateFormat formatter.timeZone = timeZone formatter.string(from: date) // This function returns date format 2024-05-23T11:16:24.706 a.m.Z
6
0
360
Jun ’24
where is macOS APIs including user space file system support?
Hi there, From "Platforms State of the Union" Video macOS section I know macOS has new API of user space file system and iPhone mirroring, and delivers new APIs including user space file system support and major improvements to MapKit. But I lookup the API diff, I don't find any added API. Where can I find the user space file system API ? I really want to develop an APP which need user space file system API. Platforms State of the Union Video corresponding timeline detail: https://youtu.be/YJZ5YcMsgD4?t=3153
7
1
312
Jun ’24
Crash objc_retain_x0
Attaching several crash traces: 2024-02-29_22-48-33.6864_-0600-3f948243e21b4c68d77a38d9cf1cecfdfe2c1565.crash 2024-03-04_15-00-02.9335_-0600-75000cd5acd63ba1434f2ffb3648b97259dddb88.crash 2024-03-05_08-55-47.2097_-0500-f682b25663107ad46f091d65f402f2be31f3f3c6.crash 2024-03-11_08-09-00.4057_-0400-e37d1a635d51afbb67ac38b42dd79c1718a408e8.crash 2024-03-15_16-20-22.6446_-0600-d4ebccf455e8305038ca564a39a5661a1dce6231.crash The final code: - (NSObject*)objectAtIndex:(NSUInteger)index { if (index < self.count) { return [self.embeddedArray objectAtIndex:index]; } else { [PNDErrorReporting reportError:PNDErrorReasonTypeSafeCollectionCrashPrevented message:@"Error msg"]; return nil; } } We subclass NSMutableArray to prevent potential crashes. but we encounter a new crash in our sdk for one of the clients. Also we noticed the stack trace skipped one of the frames (stack calls) in the crash report, in which cases the stack trace wont be identical to the actual code (beside inline)?
8
0
317
Jun ’24
URLSessionWebSocketTask - sendPing's pongReceiveHandler called twice
Hello, I'm working on adding a URLSessionWebSocketTask based web socket connection to have live data in a single view. When the user navigates to it, the connection is established and live data is received. The task is being cancelled when this view disappears: task.cancel(with: .goingAway, reason: nil) After calling resume() on the task, I ping the server to see if the connection works before sending any messages. I opt to use async API instead of closure based wherever possible. Foundation provides both APIs for most URLSessionWebSocketTask's methods, but for some reason it misses async version of sendPing. Such method, however, is available in swift-corelibs-foundation project here. So I've added a similar code locally: extension URLSessionWebSocketTask { func sendPing() async throws { let _: Void = try await withCheckedThrowingContinuation { continuation in sendPing { error in if let error { continuation.resume(throwing: error) } else { continuation.resume() } } } } } The issue that I have is that if the user navigates from the view after sendPing was called, but before pong is received, pongReceiveHandler is called twice with error: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSDescription=Software caused connection abort} This results in an exception: Fatal error: SWIFT TASK CONTINUATION MISUSE: sendPing() tried to resume its continuation more than once, throwing Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSDescription=Software caused connection abort}! There are no issues when the task is cancelled after successful ping. The documentation does not state that pongReceiveHandler is always called only once, but by looking at the code in swift-corelibs-foundation I think that it should be the case. Am I misusing sendPing, or is it a bug in the Foundation? Perhaps there is no func sendPing() async throws for some reason? I use Xcode 15.3 with Swift 5.10. Great thanks for any help. Best Regards, Michal Pastwa
3
1
273
Jun ’24
"Unexpectedly found nil while unwrapping an Optional value" in URL
Before anyone rants and raves about checking documentation - I have spent the last 4 hours trying to solve this issue on my own before asking for help. Coding in Swift is VERY new for me and I'm banging my head against the wall trying to teach myself. I am very humbly asking for help. If you refer me to documentation, that's fine but I need examples or it's going to go right over my head. Teaching myself is hard, please don't make it more difficult. I have ONE swift file with everything in it. import Foundation import Cocoa import Observation class GlobalString: ObservableObject { @Published var apiKey = "" @Published var link = "" } struct ContentView: View { @EnvironmentObject var globalString: GlobalString var body: some View { Form { Section(header: Text("WallTaker for macOS").font(.title)) { TextField( "Link ID:", text: $globalString.link ) .disableAutocorrection(true) TextField( "API Key:", text: $globalString.apiKey ) .disableAutocorrection(true) Button("Take My Wallpaper!") { } } .padding() } .task { await Wallpaper().fetchLink() } } } @main struct WallTaker_for_macOSApp: App { @AppStorage("showMenuBarExtra") private var showMenuBarExtra = true @EnvironmentObject var globalString: GlobalString var body: some Scene { WindowGroup { ContentView() .environmentObject(GlobalString()) } // MenuBarExtra("WallTaker for macOS", systemImage: "WarrenHead.png", isInserted: $showMenuBarExtra) { // Button("Refresh") { //// currentNumber = "1" // } // Button("Love It!") { //// currentNumber = "2" // } // Button("Hate It!") { //// currentNumber = "3" // } // Button("EXPLOSION!") { // // currentNumber = "3" // } //// // } } } class Wallpaper { var url: URL? = nil var lastPostUrl: URL? = nil let mainMonitor: NSScreen init() { mainMonitor = NSScreen.main! } struct LinkResponse: Codable { var post_url: String? var set_by: String? var updated_at: String } struct Link { var postUrl: URL? var setBy: String var updatedAt: Date } func parseIsoDate(timestamp: String) -> Date? { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" return formatter.date(from: timestamp) } func fetchLink() async { do { url = URL(string: GlobalString().link) let (data, _) = try await URLSession.shared.data(from: url!) let decoder = JSONDecoder() let linkResponse = try decoder.decode(LinkResponse.self, from: data) let postUrl: URL? = linkResponse.post_url != nil ? URL(string: linkResponse.post_url!) : nil let date = parseIsoDate(timestamp: linkResponse.updated_at) let link = Link( postUrl: postUrl, setBy: linkResponse.set_by ?? "anon", updatedAt: date ?? Date() ) try update(link: link) } catch { } } func update(link: Link) throws { guard let newPostUrl = link.postUrl else { return } if (newPostUrl != lastPostUrl) { lastPostUrl = newPostUrl let tempFilePath = try getTempFilePath() try downloadImageTo(sourceURL: newPostUrl, destinationURL: tempFilePath) try applyWallpaper(url: tempFilePath) } else { } } private func applyWallpaper(url: URL) throws { try NSWorkspace.shared.setDesktopImageURL(url, for: mainMonitor, options: [:]) } private func getTempFilePath() throws -> URL { let directory = NSTemporaryDirectory() let fileName = NSUUID().uuidString let fullURL = NSURL.fileURL(withPathComponents: [directory, fileName])! return fullURL } private func downloadImageTo(sourceURL: URL, destinationURL: URL) throws { let data = try Data(contentsOf: sourceURL) try data.write(to: destinationURL) } } The 'fetchLink' function is where things explode, specifically when setting the URL. I do not know what I'm doing wrong.
5
0
490
Jun ’24
Why does NSAttributedString's NSItemProviderWriting implementation not transfer custom attributes that implement Codable?
I am working on supporting some formatted text editing in my app, and I've been experimenting with copy and paste support for formatted text. I discovered that NSAttributedString implements NSItemProviderWriting, which means I can give it to UIPasteboard via setObjects and all the built-in attributes transfer perfectly if I then paste it into another text view, or even another app that behaves itself. But if I have custom attributes in my attributed string, having their values implement Codable doesn't let them transfer across the clipboard. In my implementation of textPasteConfigurationSupporting(_: transform:), I try to get an attributed string like this: let attr = item.itemProvider.loadObject(ofClass: NSAttributedString.self) { val, err in //...handle here } I get an error like this: Error Domain=NSItemProviderErrorDomain Code=-1000 "Cannot load representation of type com.apple.uikit.attributedstring" UserInfo={NSLocalizedDescription=Cannot load representation of type com.apple.uikit.attributedstring, NSUnderlyingError=0x600003e7bea0 {Error Domain=NSCocoaErrorDomain Code=260 "The file “b036c42113e34c2f9d9af14d6fefcbd534f627d6” couldn’t be opened because there is no such file." UserInfo={NSURL=file:///Users/username/Library/Developer/CoreSimulator/Devices/86E8BDD4-B6AA-4170-B0EB-57C74EC7DDF0/data/Library/Caches/com.apple.Pasteboard/eb77e5f8f043896faf63b5041f0fbd121db984dd/b036c42113e34c2f9d9af14d6fefcbd534f627d6, NSFilePath=/Users/username/Library/Developer/CoreSimulator/Devices/86E8BDD4-B6AA-4170-B0EB-57C74EC7DDF0/data/Library/Caches/com.apple.Pasteboard/eb77e5f8f043896faf63b5041f0fbd121db984dd/b036c42113e34c2f9d9af14d6fefcbd534f627d6, NSUnderlyingError=0x600003e7ac70 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}}} But I tried making my custom attribute values implement NSSecureCoding, and then it worked. Why is Codable conformance not enough here? Is it because the code that serializes and deserializes is still in Objective-C and isn't aware of Codable? Will this change as the open-source Foundation in Swift work continues?
1
0
630
Jun ’24
NSarray crashes with different exceptions from the same place
It seems that that all the crashes are coming from the same place BUT the error is slightly different. Attaching the code that responsible for the crash: static NSString * const kDelimiter = @"#$@"; + (PNDArray *)getObjectsFromData:(NSData *)data { NSString *dataStr = [[NSString alloc] initWithData:data encoding:encoding]; dataStr = [dataStr stringByReplacingOccurrencesOfString:@"\\u0000" withString:@""]; NSArray *components = [dataStr componentsSeparatedByString:kDelimiter]; NSMutableArray *result = [NSMutableArray array]; for (NSString *jsonStr in components) { if (jsonStr != nil && jsonStr.length != 0 && ![jsonStr hasPrefix:kBatchUUID]) { [result addObject:jsonStr]; } } return [PNDArray arrayWithArray:result]; } 2024-04-16_17-15-34.1922_-0600-dfa2faecf702f23e3f6558bea986de4f62851761.crash 2024-04-24_04-56-53.4664_-0500-6b125d3d03b7e497b6be339c2abb52f29658824b.crash 2024-04-25_11-13-53.1326_-0700-bfe370be3eae8d65f465eac714905dd3d13aa665.crash 2024-05-03_11-47-36.6085_-0500-2793587e7ed1c02b0e4334bbc3aa0bd7f7a0cf3d.crash 2024-05-05_10-49-40.5969_-0700-4d86636b0877fceb8c0cdb9586ee16dfb0a9c934.crash
15
0
567
Jun ’24
HKObserverQuery not working in background
I'm developing a single target watchOS app that obtains HealthKit information. I have the "Background Delivery" option checked under "Signing & Capabilities" for the watch target. The app does HKObserverQueries in the foreground that work as I would expect. But when I click the Digital Crown to return to clock face, the HKObserverQuery activity stops. I'm using Xcode 15.4, on Mac 14.5 and a Apple Watch Series 4 running 10.5.
2
0
259
Jun ’24
Problem decoding AttributedString containing emoji
I am trying to encode an AttributedString to JSON and then decode it back to an AttributedString. But when the AttributedString both (1) contains emoji, and (2) has any attributes assigned, the decoding seems to fail, producing a truncated AttributedString. By dump-ing the decoded value, I can see that the full string is still in there (in the guts property) but it is missing in normal uses of the AttributedString. Below is an example that reproduces the problem. import Foundation // An arbitrary AttributedString with emoji var attrString = AttributedString("12345💕☺️💕☺️💕☺️12345") // Set an attribute (doesn't seem to matter which one) attrString.imageURL = URL(string: "http://www.dummy.com/dummy.jpg")! // Encode the AttributedString var encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let data = try! encoder.encode(attrString) // Print the encoded JSON print("encoded JSON for AttributedString:") print(String(data: data, encoding: .utf8)!) // Output from above omitted, but it looks correct with the full string represented // Decode the AttributedString and print it let decoder = JSONDecoder() let decodedAttrString = try! decoder.decode(AttributedString.self, from: data) print("decoded AttributedString:") print(decodedAttrString) // Output from above is a truncated AttributedString: // // 12345💕☺️ { // NSImageURL = http://www.dummy.com/dummy.jpg // } print("dump of AttributedString:") dump(decodedAttrString) // Interestingly, `dump` shows that the full string is still in there: // // ▿ 12345💕☺️ { // NSImageURL = http://www.dummy.com/dummy.jpg // } // ▿ _guts: Foundation.AttributedString.Guts #0 // - string: "12345💕☺️💕☺️💕☺️12345" // ▿ runs: 1 element // ... //
9
0
1.3k
Jun ’24
NSFilePresenter Does Not Seem to Work on watchOS on Device
Hi, I submitted a Feedback Report (FB13820685) but I thought I would ask here as well because maybe I am using the framework wrong. I am using NSFilePresenter to monitor changes to a folder. On macOS, iOS (simulator), iOS (device), and watchOS (simulator) it works fine. However when running on watchOS 10.5 on device, it does not appear to work at all. I created a sample project that reproduces this problem. Am I doing something wrong? It seems like this is too basic of a problem for it to be actually broken on all Apple Watches. https://github.com/jeffreybergier/NSFilePresenterBugSampleProject
0
0
210
Jun ’24
sem_t in sandbox app
Hello, For educational purpose, I try to use a POSIX semaphore sem_t instead of a dispatch_semaphore_t in a sandbox macOS Obj-C app. When using sandbox, the semaphore code creation : sem_t * _unixSemaphore; char nameSemaphore[64] = {0}; snprintf(nameSemaphore, 22, "/UnixSemaphore_sample"); _unixSemaphore = sem_open(nameSemaphore, O_CREAT, 0644, 0); fails, receiving SEM_FAILED and the errno is 78 (not implemented) However, the sem_t _unixSemaphore is created and works fine when I disable sandbox I my entitlements. Is there a way to fix this? Thank you in advance Jean Marie
4
0
362
Jun ’24
NSString.getBytes does not crash even when an invalid range is passed.
When we pass some special words, NSString.getBytes does not crash even when we pass an invalid range. It seems a bug. The below code is an example. func testNSStringGetBytes() { let originalString: String = "􁜁あ" let bufferSize = 256 var buffer = [UInt8](repeating: 0, count: bufferSize) var usedLength = 0 // An invalid range is passed let range = NSRange(location: 0, length: originalString.count + 1) var remainingRange = NSRange() (originalString as NSString) .getBytes( &buffer, maxLength: bufferSize, usedLength: &usedLength, encoding: String.Encoding.utf8.rawValue, options: [], range: range, remaining: &remainingRange ) print("Used Length: \(usedLength)") print("Buffer: \(buffer[0..<usedLength])") if remainingRange.length > 0 { print("Did not convert the whole string. Remaining range: \(remainingRange)") } else { print("Entire string was converted successfully.") } }
1
0
289
Jun ’24
Archiving my macOS target app fails with BOOL error
I'm building a macOS target for my App (which also has some Obj-C code). Building and running the app is fine but when I archive the app in XCode, the process / build fails with the following error Type 'BOOL' (aka ;Int32') cannot be used as a boolean;test for '!=0' instead It happens in a couple of places, one of the places being private func getRootDirectory(createIfNotExists: Bool = true) throws -> URL { return try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) } where it complains that create: true is not acceptable and throws the above error. If I comment out this line, the archive works successfully. When i Cmd + click the definition of Filemanager.default.url , i get this @available(macOS 10.6, *) open func url(for directory: FileManager.SearchPathDirectory, in domain: FileManager.SearchPathDomainMask, appropriateFor url: URL?, create shouldCreate: BOOL) throws -> URL This looks fishy since it it says create shouldCreate: BOOL whereas the documentation says it should be just Bool func url( for directory: FileManager.SearchPathDirectory, in domain: FileManager.SearchPathDomainMask, appropriateFor url: URL?, create shouldCreate: Bool ) throws -> URL My minimum deployment target is macOS 13.0 I'm quite stumped at this error - which happens only while archiving. Does anybody know why?
4
0
406
Jun ’24
CGRectMake: symbol not found when using dlopen/dlsym
The following program demonstrates the issue. It prints: y = 2.000000 CGRectMake symbol not found What would cause the symbol not to be found when using the dlopen/dlsym functions? #import <CoreGraphics/CoreGraphics.h> #import <dlfcn.h> int main(int argc, const char * argv[]) { CGRect rect = CGRectMake(1.0, 2.0, 3.0, 4.0); printf("y = %f\n", rect.origin.y); void * handle = dlopen("/System/Library/Frameworks/CoreGraphics.framework/Versions/A/CoreGraphics", RTLD_LAZY); if (handle == NULL) { printf("handle == NULL\n"); } else if (dlsym(handle, "CGRectMake") == NULL) { printf("CGRectMake symbol not found\n"); } return 0; } I am observing this issue with other symbols as well. What is special about them?
1
0
259
Jun ’24
loaded array from plist. call using AppDelegate() returns empty array.
In app delegate I'm trying to load an array with strings from a plist. I print the plist it prints fine... func loadTypesArray() { guard let path = Bundle.main.path(forResource: "Types", ofType: "plist") else {return} let url = URL(fileURLWithPath: path) let data = try! Data(contentsOf: url) guard let plist = try! PropertyListSerialization.propertyList(from: data, options: .mutableContainers, format: nil) as? [String] else {return} print(plist) typesArray = plist // print(typesArray) } But when I try and access it from a different part of the app using let typesArray = AppDelegate().typesArray the array I get is an empty array! any help?
2
0
348
Jun ’24