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.5k
Feb ’24
iOS Socket cannot connect ipv6 address when use PacketTunnelProvider
I'm use iPad OS 17.5.1, when I try to use socket to connect to an ipv6 address created by PacketTunnelProvider in my iOS device, an error occurs. Here is the code to create socket server and client: #include <stdio.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> int dx_create_ipv6_server(const char *ipv6_address, int port) { int server_fd; struct sockaddr_in6 server_addr; server_fd = socket(AF_INET6, SOCK_STREAM, 0); if (server_fd == -1) { perror("socket() failed"); return -1; } memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin6_family = AF_INET6; server_addr.sin6_port = htons(port); if (inet_pton(AF_INET6, ipv6_address, &server_addr.sin6_addr) <= 0) { perror("inet_pton() failed"); close(server_fd); return -1; } if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) { perror("bind() failed"); close(server_fd); return -1; } if (listen(server_fd, 5) == -1) { perror("listen() failed"); close(server_fd); return -1; } printf("Server is listening on [%s]:%d\n", ipv6_address, port); return server_fd; } int dx_accept_client_connection(int server_fd) { int client_fd; struct sockaddr_in6 client_addr; socklen_t client_addr_len = sizeof(client_addr); client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_len); if (client_fd == -1) { perror("accept() failed"); return -1; } char client_ip[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, &client_addr.sin6_addr, client_ip, sizeof(client_ip)); printf("Client connected: [%s]\n", client_ip); return client_fd; } int dx_connect_to_ipv6_server(const char *ipv6_address, int port) { int client_fd; struct sockaddr_in6 server_addr; client_fd = socket(AF_INET6, SOCK_STREAM, 0); if (client_fd == -1) { perror("socket() failed"); return -1; } memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin6_family = AF_INET6; server_addr.sin6_port = htons(port); if (inet_pton(AF_INET6, ipv6_address, &server_addr.sin6_addr) <= 0) { perror("inet_pton() failed"); close(client_fd); return -1; } if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) { perror("connect() failed"); close(client_fd); return -1; } printf("Connected to server [%s]:%d\n", ipv6_address, port); close(client_fd); return 0; } @implementation SocketTest + (void)startSever:(NSString *)addr port:(int)port { [[NSOperationQueue new] addOperationWithBlock:^{ int server_fd = dx_create_ipv6_server(addr.UTF8String, port); if (server_fd == -1) { return; } int client_fd = dx_accept_client_connection(server_fd); if (client_fd == -1) { close(server_fd); return; } close(client_fd); close(server_fd); }]; } + (void)clientConnect:(NSString *)addr port:(int)port{ [[NSOperationQueue new] addOperationWithBlock:^{ dx_connect_to_ipv6_server(addr.UTF8String, port); }]; } @end PacketTunnelProvider code: override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) { let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "fd84:306d:fc4e::1") let ipv6 = NEIPv6Settings(addresses: ["fd84:306d:fc4e::1"], networkPrefixLengths: 64) settings.ipv6Settings = ipv6 setTunnelNetworkSettings(settings) { error in if error == nil { self.readPackets() } completionHandler(error) } } private func readPackets() { // do nothing packetFlow.readPackets { [self] packets, protocols in self.packetFlow.writePackets(packets, withProtocols: protocols) self.readPackets() } } At main target, in viewcontroller's viewDidAppear, after starting the VPN, executed following code: [SocketTest startSever:@"fd84:306d:fc4e::1" port:12345]; sleep(3); [SocketTest clientConnect:@"fd84:306d:fc4e::1" port:12345]; The startSever is executed correctly, but when executing: connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) in clientConnect, the code is blocked until it times out and returns -1. **Even if I use GCDAsyncSocket or BlueSocket, I get the same error. The strange thing is that if I use the ipv4 address in PacketTunnelProvider, and change the above code to the ipv4 version and connect to ipv4 address, or use GCDAsyncSocket to perform the corresponding operation, it can be executed correctly. ** I tried to search Google for problems with ios-related ipv6 addresses, but I still couldn't find a solution. Is this a bug in the ios system or is there something wrong with my code? I hope to get your help! Stackoverflow url: iOS Socket cannot connect ipv6 address when use PacketTunnelProvider
1
0
25
8h
macos Objective-C openURL failed
error: Error Domain=NSCocoaErrorDomain Code=256 "The application “Google Chrome” could not be launched because a miscellaneous error occurred." UserInfo={NSURL=file:///Applications/Google%20Chrome.app/, NSLocalizedDescription=The application “Google Chrome” could not be launched because a miscellaneous error occurred., NSUnderlyingError=0x6000038376c0 {Error Domain=RBSRequestErrorDomain Code=5 "Launch failed." UserInfo={NSLocalizedFailureReason=Launch failed., NSUnderlyingError=0x6000038349f0 {Error Domain=OSLaunchdErrorDomain Code=112 "Could not find specified domain" UserInfo={NSLocalizedFailureReason=Could not find specified domain}}}}}
0
0
21
8h
iOS Socket cannot connect ipv6 address when use PacketTunnelProvider
When I try to use socket to connect to an ipv6 address created by PacketTunnelProvider in my iOS device, an error occurs. Here is the code to create socket server and client: #include <stdio.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> int dx_create_ipv6_server(const char *ipv6_address, int port) { int server_fd; struct sockaddr_in6 server_addr; server_fd = socket(AF_INET6, SOCK_STREAM, 0); if (server_fd == -1) { perror("socket() failed"); return -1; } memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin6_family = AF_INET6; server_addr.sin6_port = htons(port); if (inet_pton(AF_INET6, ipv6_address, &server_addr.sin6_addr) <= 0) { perror("inet_pton() failed"); close(server_fd); return -1; } if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) { perror("bind() failed"); close(server_fd); return -1; } if (listen(server_fd, 5) == -1) { perror("listen() failed"); close(server_fd); return -1; } printf("Server is listening on [%s]:%d\n", ipv6_address, port); return server_fd; } int dx_accept_client_connection(int server_fd) { int client_fd; struct sockaddr_in6 client_addr; socklen_t client_addr_len = sizeof(client_addr); client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_len); if (client_fd == -1) { perror("accept() failed"); return -1; } char client_ip[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, &client_addr.sin6_addr, client_ip, sizeof(client_ip)); printf("Client connected: [%s]\n", client_ip); return client_fd; } int dx_connect_to_ipv6_server(const char *ipv6_address, int port) { int client_fd; struct sockaddr_in6 server_addr; client_fd = socket(AF_INET6, SOCK_STREAM, 0); if (client_fd == -1) { perror("socket() failed"); return -1; } memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin6_family = AF_INET6; server_addr.sin6_port = htons(port); if (inet_pton(AF_INET6, ipv6_address, &server_addr.sin6_addr) <= 0) { perror("inet_pton() failed"); close(client_fd); return -1; } if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) { perror("connect() failed"); close(client_fd); return -1; } printf("Connected to server [%s]:%d\n", ipv6_address, port); close(client_fd); return 0; } @implementation SocketTest + (void)startSever:(NSString *)addr port:(int)port { [[NSOperationQueue new] addOperationWithBlock:^{ int server_fd = dx_create_ipv6_server(addr.UTF8String, port); if (server_fd == -1) { return; } int client_fd = dx_accept_client_connection(server_fd); if (client_fd == -1) { close(server_fd); return; } close(client_fd); close(server_fd); }]; } + (void)clientConnect:(NSString *)addr port:(int)port{ [[NSOperationQueue new] addOperationWithBlock:^{ dx_connect_to_ipv6_server(addr.UTF8String, port); }]; } @end PacketTunnelProvider code: override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) { let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "fd84:306d:fc4e::1") let ipv6 = NEIPv6Settings(addresses: ["fd84:306d:fc4e::1"], networkPrefixLengths: 64) settings.ipv6Settings = ipv6 setTunnelNetworkSettings(settings) { error in if error == nil { self.readPackets() } completionHandler(error) } } private func readPackets() { // do nothing packetFlow.readPackets { [self] packets, protocols in self.packetFlow.writePackets(packets, withProtocols: protocols) self.readPackets() } } At main target, in viewcontroller's viewDidAppear, after starting the VPN, executed following code: [SocketTest startSever:@"fd84:306d:fc4e::1" port:12345]; sleep(3); [SocketTest clientConnect:@"fd84:306d:fc4e::1" port:12345]; The startSever is executed correctly, but when executing: connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) in clientConnect, the code is blocked until it times out and returns -1. Even if I use GCDAsyncSocket or BlueSocket, I get the same error. The strange thing is that if I use the ipv4 address in PacketTunnelProvider, and change the above code to the ipv4 version and connect to ipv4 address, or use GCDAsyncSocket to perform the corresponding operation, it can be executed correctly. I tried to search Google for problems with ios-related ipv6 addresses, but I still couldn't find a solution. Is this a bug in the ios system or is there something wrong with my code? I hope to get your help!
0
0
13
8h
Memory crash at String._bridgeToObjectiveCImpl()
I'll describe my crash with an example, looking for some insights into the reason why this is happening. @objc public protocol LauncherContainer { var launcher: Launcher { get } } @objc public protocol Launcher: UIViewControllerTransitioningDelegate { func initiateLaunch(url: URL, launchingHotInstance: Bool) } @objc final class LauncherContainer: NSObject, LauncherContainer, TabsContentCellTapHandler { ... init( ... ) { ... super.init() } ... // // ContentCellTapHandler // public func tabContentCellItemDidTap( tabId: String ) { ... launcher.initiateNewTabNavigation( tabId: tabId // Crash happens here ) } public class Launcher: NSObject, Launcher, FooterPillTapHandler { public func initiateNewTabNavigation(tabId: String) { ... } } public protocol TabsContentCellTapHandler: NSObject { func tabContentCellItemDidTap( tabId: String, }
2
0
90
10h
Memory crash at String._bridgeToObjectiveCImpl()
I'll describe my crash with an example, looking for some insights into the reason why this is happening. @objc public protocol LauncherContainer { var launcher: Launcher { get } } @objc public protocol Launcher: UIViewControllerTransitioningDelegate { func initiateLaunch(url: URL, launchingHotInstance: Bool) } @objc final class LauncherContainer: NSObject, LauncherContainer, TabsContentCellTapHandler { ... init( ... ) { ... super.init() } ... // // ContentCellTapHandler // public func tabContentCellItemDidTap( tabId: String ) { ... launcher.initiateNewTabNavigation( tabId: tabId // Crash happens here ) } public class Launcher: NSObject, Launcher, FooterPillTapHandler { public func initiateNewTabNavigation(tabId: String) { ... } } public protocol TabsContentCellTapHandler: NSObject { func tabContentCellItemDidTap( tabId: String, } Crash stack last 2 lines are- libswiftCore.dylib swift_unknownObjectRetain libswiftCore.dylib String._bridgeToObjectiveCImpl() String._bridgeToObjectiveCImpl() gets called when the caller and implementation is in Swift file I believe due to @objc class LauncherContainer there'd be bridging header generated. Does that mean tabId passed to tabContentCellItemDidTap is a String but the one passed to initiateNewTabNavigation is NSString? TabId is UUID().uuidString if that helps. Wondering if UUID().uuidString has something to do with this. Thanks a ton for helping. Please find attached screenshot of the stack trace.
1
0
96
13h
Directly operating on memory pointed by UnsafeMutableRawPointer
In my project, i have a Swift class with a class level property of type string. Like this : class TWSwiftString { var pString:String! init(_ pString: String) { self.pString = pString } } I am creating intance of this class and then creating a opaque pointer to this intance. Like this : let str = TWSwiftString("World") // Increasing RC by 1 strptr = Unmanaged.passRetained(str).toOpaque() Now using this opaque pointer i want to modify the value of pString by directly operating on memory. Like this: withUnsafeMutablePointer(to: &strptr.pString) { strPointer in strPointer.pointee = "World" } Although i am able to modify pString like this and print. Lets assume i have a approach to make sure memory remains valid when it is operated on and freeing of memory is also handled somehow . Will this approach work if i have 100s of intance of this string which are being operated in this manner ? What if the size of new value is greater than existing string value ? For this i am thinking of chunk of memory initially and then keep on increasing size of it as bigger string then this chunk comes. Does this approach seems feasible ? Any other problems i can encounter by using this approach ? Chatgpt gave this answer : To directly update the memory of a Swift class’s property, particularly to alter a String property, is generally discouraged due to Swift's memory safety model. However, if we want to access and modify a class property directly, the best practice is to use a property accessor, as manually altering memory could lead to undefined behavior or even crashes. Why Direct Memory Manipulation Is Risky When you attempt to manipulate memory directly, especially with Swift’s memory model, you might alter not only the value but also the memory layout of Swift’s String type, which could break things internally. The Swift compiler may store String differently based on the internal structure, so even if we manage to locate the correct memory address, directly modifying it is unreliable. do you have any opinion around chatgpt resoponse ?
1
0
57
1d
DST, DateEncodingStrategy.iso8601, and UTC Fun
Hello, My code calls a macOS system library which returns Foundation Date properties. I have a program that will run every night, and output the data via the Swift JSONEncoder and uses DateEncodingStrategy.iso8601. As you likely know, a DST shift happened over the weekend here in the US. In my output, every single Date changed by 1 hour, despite the fact that nothing in the underlying data changed overnight. Here is an example diff in the output. I see the "Z", which I think should not be affected by DST changes. - "dateAdded" : "2003-12-15T17:02:56Z", - "dateModified" : "2007-03-07T04:31:16Z", + "dateAdded" : "2003-12-15T18:02:56Z", + "dateModified" : "2007-03-07T05:31:16Z", Here is a sample of the data: public struct Track: Codable, Hashable { var dateAdded: Date? var dateModified: Date? } And the encoding is here: extension Array where Element == Track { public func jsonData() throws -> Data { let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] encoder.dateEncodingStrategy = .iso8601 return try encoder.encode(self) } } Pretty basic stuff overall. So my questions are: Am I correct in my assumption that .iso8601 is UTC, and that UTC is daylight savings shift agnostic? Is this the right way to ensure the my JSON is encoded in UTC? If the library I am calling is building its Date incorrectly, how may I work around the problem? I'm not reporting the library name right now, in order to ensure that my code is doing the right thing without assumptions. Thanks for any tips!
3
0
96
1d
Which thread to call uploadTask from URLSession
Hi, I would like to know if it is safe to call the uploadTask from URLSession from the main thread ? We've a user who is reporting repeated crashes at startup, here is the stack we see: Exception Type: EXC_CRASH (SIGKILL) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: FRONTBOARD 2343432205 <RBSTerminateContext| domain:10 code:0x8BADF00D explanation:scene-update watchdog transgression: app<com.appspot.myApp(E7590BB1-722C-491D-9199-F867DE4B880A)>:2212 exhausted real (wall clock) time allowance of 10.00 seconds ProcessVisibility: Background ProcessState: Running WatchdogEvent: scene-update WatchdogVisibility: Background WatchdogCPUStatistics: ( "Elapsed total CPU time (seconds): 21.260 (user 10.230, system 11.030), 35% CPU", "Elapsed application CPU time (seconds): 0.006, 0% CPU" ) reportType:CrashLog maxTerminationResistance:Interactive> Triggered by Thread: 0 Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed: 0 libsystem_kernel.dylib 0x1def7a688 mach_msg2_trap + 8 1 libsystem_kernel.dylib 0x1def7dd98 mach_msg2_internal + 80 2 libsystem_kernel.dylib 0x1def7dcb0 mach_msg_overwrite + 424 3 libsystem_kernel.dylib 0x1def7dafc mach_msg + 24 4 libdispatch.dylib 0x1968d8f14 _dispatch_mach_send_and_wait_for_reply + 544 5 libdispatch.dylib 0x1968d92b4 dispatch_mach_send_with_result_and_wait_for_reply + 60 6 libxpc.dylib 0x21714a930 xpc_connection_send_message_with_reply_sync + 256 7 Foundation 0x18d80a3ac __NSXPCCONNECTION_IS_WAITING_FOR_A_SYNCHRONOUS_REPLY__ + 16 8 Foundation 0x18d806b14 -[NSXPCConnection _sendInvocation:orArguments:count:methodSignature:selector:withProxy:] + 2160 9 CoreFoundation 0x18eb868dc ___forwarding___ + 1004 10 CoreFoundation 0x18eb86430 _CF_forwarding_prep_0 + 96 11 CFNetwork 0x1900c71e0 -[__NSURLBackgroundSession setupBackgroundSession] + 800 12 CFNetwork 0x1900b3e80 -[__NSURLBackgroundSession initWithConfiguration:delegate:delegateQueue:delegateDispatchQueue:] + 552 13 CFNetwork 0x1900b4784 +[NSURLSession _sessionWithConfiguration:delegate:delegateQueue:delegateDispatchQueue:] + 1496 14 MyApp 0x1054210b4 CombineBgXferRepository.session.getter (in MyApp) (CombineBgXferRepository.swift:62) + 7966900 15 MyApp 0x105422fa4 CombineBgXferRepository.startUploadTask(fileURL:request:) (in MyApp) (CombineBgXferRepository.swift:310) + 7974820 If it is ok to call this uploadTask from the main thread, does this crash indicate a problem with the operating system? Are there scenarios where the background upload service does not respond to requests?
3
2
114
2d
Setting up app lunch argument using ProcessInfo.processInfo.arguments not working in iOS 18
Hi, I'm trying to set up FIRDebugEnabled as launch arguments in app delegate based on user choice using ProcessInfo.processInfo.arguments. Which is working fine in iOS 17 and below devices and stoped working in iOS 18 Here is my sample, if condition { var arguments = ProcessInfo.processInfo.arguments arguments.append("-FIRDebugEnabled") ProcessInfo.processInfo.setValue(arguments, forKey: "arguments") }
2
0
139
6d
Directory NSFileWrapper does not update fileWrappers after removeItem
Hi, I encounter unexpected behavior from the FileWrapper updates that occurs when I remove file using FileManager.removeItem If I first remove a file from the directory, then create NSFileWrapper instance, I get unexpected values from calls to matchesContents(of:) import Foundation let copyURL = URL(filePath: "/Users/marcinkrzyzanowski/Downloads/filewrappertest.test/COPY.png") // THIS OPERATION BREAKS IT. REMOVE IT TO WORK AS EXPECTED try! FileManager().removeItem(at: copyURL) let dirURL = URL(filePath: "/Users/marcinkrzyzanowski/Downloads/filewrappertest.test") let fw = try FileWrapper(url: dirURL) fw.fileWrappers // ["IMG_0736.png"] try FileManager.default.copyItem(at: URL(filePath: "/Users/marcinkrzyzanowski/Downloads/filewrappertest.test/IMG_0736.png"), to: copyURL) fw.fileWrappers // ["IMG_0736.png"] fw.matchesContents(of: dirURL) // true (expected: false) try fw.read(from: dirURL) fw.fileWrappers! // ["COPY.png", "IMG_0736.png"] fw.matchesContents(of: dirURL) // true I don't understand why the "FileManager.removeItem" affects the NSFileWrapper behavior in such a way. It does not change even when I add a delay after removeItem. Any idea?
1
0
158
2w
Managed configuration in iOS app and Action Extension
Hi, I have a question regarding reading the configuration of a managed app deployed via an MDM system. The application has an Action Extension and can receive shared files via this extension. The problem I am facing is that I can read the managed configuration in the host app by accessing the UserDefaults.standard.object(forKey: "com.apple.configuration.managed") dictionary. With this, I can configure the host app. However, I am unable to read this configuration key in the Action Extension part of the application. My question is whether there is any possibility to read the managed configuration even in the extension. So far, I have been unable to figure out how to read it. I found the sample code, but it was not very helpful since it is very basic and does not deal with extensions at all. Any hints are appreciated.
1
0
206
2w
Errors codes for invalid resumeData with URLSession UploadTask?
I'm coding resumable uploads using iOS 17's URLSession's uploadTask(withResumeData:. This function returns a non-Optional URLSessionUploadTask and does not throw. In cases where the system determines the resumeData is no longer valid, how do I detect that (so I can create a new URLSessionUploadTask from scratch)? I'm doing this for background uploads, so it's all URLSessionDelegate apis, but what are the failure modes, and what Error types and Codes would we get specially? Obviously, I expect the resume data is no longer usable or necessary when get a server success i.e. in the 2xx range. Does the resume data also become invalid for other server responses, like 4xx's? or 5xx's?. I expect the resume data usually shouldn't become invalid when getting URLError's like .networkConnectionLost, since that's like half the point of having the feature in the first place, to resume after the a broken network connection. But I do expect that if the resumeData is invalid, then I should be able to reach the server and get a server response, so in that case what Code would we get? I'm assuming the system is caching our upload file somewhere, and the resume data somehow makes a reference to it, so does that file get optimized away at some point in time when left untouched, and need us to start a fresh upload? We are also saving the file for potential future re-uploads, until we get certain assurances of completion from our backend, but I am just wondering on which logic branches I need to determine that the resumeData I thought I could use is no longer usable.
3
0
133
3w
An issue with DateComponents
The expected number of months for the below code should be -48 months. It used to work like this Until iOS17. Now when building with iOS 18 it gives -47 months. Changing the two dates with one day back works as expected import Foundation var calendar = Calendar(identifier: .gregorian) calendar.timeZone = .gmt let components1 = DateComponents( calendar: calendar, year: 2004, month: 2, day: 29 //28 in case of changing day to 28 it works as expected ) guard let date1 = components1.date else { exit(1) } let components2 = DateComponents( calendar: calendar, year: 2008, month: 2, day: 29 //28 in case of changing day to 28 it works as expected ) guard let date2 = components2.date else { exit(1) } print(date1) print(date2) let months = calendar.dateComponents([.month, .isLeapMonth], from: date2, to: date1) print(months)
1
0
182
3w
NSProcessInfo operatingSystemVersion generates warning CFPropertyListCreateFromXMLData(): Old-style plist parser: missing semicolon in dictionary
Consider this very trivial code which accesses the operatingSystemVersion property of NSProcessInfo as documented at https://developer.apple.com/documentation/foundation/nsprocessinfo/1410906-operatingsystemversion osversion.c: #include <Foundation/Foundation.h> int main(int argc, char *argv[]) { NSOperatingSystemVersion osVersion = [[NSProcessInfo processInfo] operatingSystemVersion]; fprintf(stderr, "OS version: %ld.%ld.%ld\n", osVersion.majorVersion, osVersion.minorVersion, osVersion.patchVersion); } Compile it: /usr/bin/clang -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.1.sdk -iframework /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.1.sdk/System/Library/Frameworks -x objective-c -o a.out -framework Foundation osversion.c Then run it: ./a.out It works fine and prints the OS version: OS version: 14.6.1 Run it again and pass it some arbitrary program arguments: ./a.out foo bar Still continues to work fine and prints the output: OS version: 14.6.1 Now run it again and this time pass it two program arguments, the first one being - and the second one being something of the form {x=y} ./a.out - {x=y} This time notice how it prints a couple of warning logs from CFPropertyListCreateFromXMLData before printing the output: 2024-10-11 11:18:03.584 a.out[61327:32412190] CFPropertyListCreateFromXMLData(): Old-style plist parser: missing semicolon in dictionary on line 1. Parsing will be abandoned. Break on _CFPropertyListMissingSemicolon to debug. 2024-10-11 11:18:03.585 a.out[61327:32412190] CFPropertyListCreateFromXMLData(): Old-style plist parser: missing semicolon in dictionary on line 1. Parsing will be abandoned. Break on _CFPropertyListMissingSemicolon to debug. OS version: 14.6.1 As far as I can see there's nothing wrong in the code nor the user inputs to the program. Is this some issue in the internal implementation of NSProcessInfo? Should this be reported as an issue through feedback assistant (which category)? Although this example was run on 14.6.1 of macos, the issue is reproducible on older versions too.
5
0
278
3w
NSDirectoryEnumerator returns nil
I'm trying to display my images in a tableView, I'm using NSFIleManager and NSDirectoryEnumerator to get all files in the current folder: NSString *path = @"/Users/eagle/Documents/avatars"; NSFileManager *fileManager = NSFileManager.defaultManager; NSDirectoryEnumerator *directoryEnum = [fileManager enumeratorAtPath:path]; NSString *file; while (file = [directoryEnum nextObject]) { // ... } the problem is that this line file = [directoryEnum nextObject] always returns nil, what gives? I already made sure that this folder has no subfolders and contains only images, so what's the problem here?
4
0
234
4w
Crash with Progress type, Swift 6, iOS 18
We are getting a crash _dispatch_assert_queue_fail when the cancellationHandler on NSProgress is called. We do not see this with iOS 17.x, only on iOS 18. We are building in Swift 6 language mode and do not have any compiler warnings. We have a type whose init looks something like this: init( request: URLRequest, destinationURL: URL, session: URLSession ) { progress = Progress() progress.kind = .file progress.fileOperationKind = .downloading progress.fileURL = destinationURL progress.pausingHandler = { [weak self] in self?.setIsPaused(true) } progress.resumingHandler = { [weak self] in self?.setIsPaused(false) } progress.cancellationHandler = { [weak self] in self?.cancel() } When the progress is cancelled, and the cancellation handler is invoked. We get the crash. The crash is not reproducible 100% of the time, but it happens significantly often. Especially after cleaning and rebuilding and running our tests. * thread #4, queue = 'com.apple.root.default-qos', stop reason = EXC_BREAKPOINT (code=1, subcode=0x18017b0e8) * frame #0: 0x000000018017b0e8 libdispatch.dylib`_dispatch_assert_queue_fail + 116 frame #1: 0x000000018017b074 libdispatch.dylib`dispatch_assert_queue + 188 frame #2: 0x00000002444c63e0 libswift_Concurrency.dylib`swift_task_isCurrentExecutorImpl(swift::SerialExecutorRef) + 284 frame #3: 0x000000010b80bd84 MyTests`closure #3 in MyController.init() at MyController.swift:0 frame #4: 0x000000010b80bb04 MyTests`thunk for @escaping @callee_guaranteed @Sendable () -&gt; () at &lt;compiler-generated&gt;:0 frame #5: 0x00000001810276b0 Foundation`__20-[NSProgress cancel]_block_invoke_3 + 28 frame #6: 0x00000001801774ec libdispatch.dylib`_dispatch_call_block_and_release + 24 frame #7: 0x0000000180178de0 libdispatch.dylib`_dispatch_client_callout + 16 frame #8: 0x000000018018b7dc libdispatch.dylib`_dispatch_root_queue_drain + 1072 frame #9: 0x000000018018bf60 libdispatch.dylib`_dispatch_worker_thread2 + 232 frame #10: 0x00000001012a77d8 libsystem_pthread.dylib`_pthread_wqthread + 224 Any thoughts on why this is crashing and what we can do to work-around it? I have not been able to extract our code into a simple reproducible case yet. And I mostly see it when running our code in a testing environment (XCTest). Although I have been able to reproduce it running an app a few times, it's just less common.
23
7
802
2w
Interpreting received "Data" object in cpp
Hello Everyone, I have a use case where I wanted to interpret the "Data" object received as a part of my NWConnection's recv call. I have my interpretation logic in cpp so in swift I extract the pointer to the raw bytes from Data and pass it to cpp as a UnsafeMutableRawPointer. In cpp it is received as a void * where I typecast it to char * to read data byte by byte before framing a response. I am able to get the pointer of the bytes by using // Swift Code // pContent is the received Data if let content = pContent, !content.isEmpty { bytes = content.withUnsafeBytes { rawBufferPointer in guard let buffer = rawBufferPointer.baseAddress else { // return with null data. } // invoke cpp method to interpret data and trigger response. } // Cpp Code void InterpretResponse (void * pDataPointer, int pDataLength) { char * data = (char *) pDataPointer; for (int iterator = 0; iterator < pDataLength; ++iterator ) { std::cout << data<< std::endl; data++; } } When I pass this buffer to cpp, I am unable to interpret it properly. Can someone help me out here? Thanks :) Harshal
3
0
543
Oct ’24
NSAttributedString.enumerateAttribute(_:in) crashes with custom attribute in macOS Sequoia
The following code crashes on macOS 15 Sequoia: import Foundation let key = NSAttributedString.Key("org.example.key") let value = Value() let string = NSMutableAttributedString() string.append(NSAttributedString(string: "a", attributes: [:])) string.append(NSAttributedString(string: "b", attributes: [key: value])) string.append(NSAttributedString(string: "c", attributes: [:])) string.enumerateAttribute(key, in: NSRange(location: 0, length: string.length)) { value, range, stop in print(range) } class Value: Equatable, Hashable { static func == (lhs: Value, rhs: Value) -> Bool { return lhs === rhs } func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } } The error is EXC_BAD_ACCESS (code=1, address=0x0) I wanted to run it on my external macOS 14 partition to confirm that it didn't crash before updating to macOS 15, but for some reason macOS will just restart and boot again into macOS 15. So I tried with macOS 13, which I was allowed to start for some reason, and I was able to confirm that the code doesn't crash. Is this a known issue, and is there a workaround? Removing the two lines that add the letters a and c, or just declaring class Value without conformance to Equatable, Hashable, interestingly, solves the issue.
5
0
284
3w