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
Fatal Exception: NSInternalInconsistencyException Attempting to select a view controller that isn't a child! (null)
When call: [UITabBarController setViewControllers:animated:] It crashed and raise an Fatal Exception: Fatal Exception: NSInternalInconsistencyException Attempting to select a view controller that isn't a child! (null) the crash stack is: Fatal Exception: NSInternalInconsistencyException 0 CoreFoundation 0x8408c __exceptionPreprocess 1 libobjc.A.dylib 0x172e4 objc_exception_throw 2 Foundation 0x82215c _userInfoForFileAndLine 3 UIKitCore 0x38a468 -[UITabBarController transitionFromViewController:toViewController:transition:shouldSetSelected:] 4 UIKitCore 0x3fa8a4 -[UITabBarController _setSelectedViewController:performUpdates:] 5 UIKitCore 0x3fa710 -[UITabBarController setSelectedIndex:] 6 UIKitCore 0x8a5fc +[UIView(Animation) performWithoutAnimation:] 7 UIKitCore 0x3e54e0 -[UITabBarController _setViewControllers:animated:] 8 UIKitCore 0x45d7a0 -[UITabBarController setViewControllers:animated:] And it appear sometimes, what's the root cause?
0
0
4
23m
copyfile causes NSPOSIXErrorDomain 12 "Cannot allocate memory" when copying symbolic link from NTFS partition
I was able to confirm with a customer of mine that calling copyfile with a source file that is a symbolic link on a NTFS partition always causes the error NSPOSIXErrorDomain 12 Cannot allocate memory They use NTFS drivers from Paragon. They tried copying a symbolic link from NTFS to both APFS and NTFS with the same result. Is this an issue with macOS, or with the NTFS driver? Copying regular files on the other hand always works. Copying manually from the Finder also seems to always work, both with regular files and symbolic links, so I'm wondering how the Finder does it. Here is the sample app that they used to reproduce the issue. The first open panel allows to select the source directory and the second one the destination directory. The variable filename holds the name of the symbolic link to be copied from the source to the destination. Apparently it's not possible to select a symbolic link directly in NSOpenPanel, as it always resolves to the linked file. @main class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ notification: Notification) { let openPanel = NSOpenPanel() openPanel.canChooseDirectories = true openPanel.canChooseFiles = false openPanel.runModal() let filename = "Modules" let source = openPanel.urls[0].appendingPathComponent(filename) openPanel.runModal() let destination = openPanel.urls[0].appendingPathComponent(filename) do { let state = copyfile_state_alloc() defer { copyfile_state_free(state) } var bsize = UInt32(16_777_216) if copyfile_state_set(state, UInt32(COPYFILE_STATE_BSIZE), &bsize) != 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) } if copyfile_state_set(state, UInt32(COPYFILE_STATE_STATUS_CB), unsafeBitCast(copyfileCallback, to: UnsafeRawPointer.self)) != 0 || copyfile_state_set(state, UInt32(COPYFILE_STATE_STATUS_CTX), unsafeBitCast(self, to: UnsafeRawPointer.self)) != 0 || copyfile(source.path, destination.path, state, copyfile_flags_t(COPYFILE_NOFOLLOW)) != 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) } } catch { let error = error as NSError let alert = NSAlert() alert.messageText = "\(error.localizedDescription)\n\(error.domain) \(error.code)" alert.runModal() } } private let copyfileCallback: copyfile_callback_t = { what, stage, state, src, dst, ctx in if what == COPYFILE_COPY_DATA { if stage == COPYFILE_ERR { return COPYFILE_QUIT } var size: off_t = 0 copyfile_state_get(state, UInt32(COPYFILE_STATE_COPIED), &size) } return COPYFILE_CONTINUE } }
0
0
66
11h
Captured photos in wrong orientation
I'm building a custom camera screen that displays the camera image on a preview layer and then captures an image, using AVCaptureSession. When the picture is captured, I immediately load it into a UIImageView in order to display it to the user for approval. I've actually done this many times before, but this is the first time I've tried to do it in an app that supports interface rotation. If I hold the phone in Portrait mode and capture a picture, everything works as expected. When the user rotates the phone into Landscape orientation, I detect this and I replace the preview layer (AVCaptureVideoPreviewLayer) with a new one, specifying connection.videoRotationAngle in order to make the image appear in the right orientation. I'm a little surprised that this is necessary, and it's not a smooth transition, but that doesn't matter. What does matter is that when I capture the image, it is in the wrong orientation. I tried rotating it myself, but this doesn't seem to make any difference. What am I doing wrong?
0
0
50
12h
Title: CoreFoundation CFRelease Crash on iOS 18
Hi everyone, I'm experiencing crashes that consistently occur on iOS 18 devices, which seem to share a common root cause. I'm hoping for some guidance. Here are the details of the crashes as received from Xcode Organizer: Crash Trace 1: 0 CoreFoundation 0x0000000192c50e54 CF_IS_OBJC + 76 (CFRuntime.c:461) 1 CoreFoundation 0x0000000192c4dd3c CFRelease + 60 (CFRuntime.c:1202) 2 CoreFoundation 0x0000000192d015e0 _signalEventSync + 252 (CFStream.c:636) 3 CoreFoundation 0x0000000192d53050 ___signalEventQueue_block_invoke + 28 (CFStream.c:646) 4 libdispatch.dylib 0x000000019a93c370 _dispatch_call_block_and_release + 32 (init.c:1549) 5 libdispatch.dylib 0x000000019a93e0d0 _dispatch_client_callout + 20 (object.m:576) 6 libdispatch.dylib 0x000000019a9456d8 _dispatch_lane_serial_drain + 744 (queue.c:3934) 7 libdispatch.dylib 0x000000019a9461e0 _dispatch_lane_invoke + 380 (queue.c:4025) 8 libdispatch.dylib 0x000000019a951258 _dispatch_root_queue_drain_deferred_wlh + 288 (queue.c:7193) 9 libdispatch.dylib 0x000000019a950aa4 _dispatch_workloop_worker_thread + 540 (queue.c:6787) 10 libsystem_pthread.dylib 0x000000021a00fc7c _pthread_wqthread + 288 (pthread.c:2696) 11 libsystem_pthread.dylib 0x000000021a00c488 start_wqthread + 8 (:-1) Crash Trace 2: 0 libobjc.A.dylib 0x0000000186f33c20 objc_msgSend + 32 1 CoreFoundation 0x0000000189cb14b8 _inputStreamCallbackFunc + 36 (CFObject.m:1952) 2 CoreFoundation 0x0000000189cb0aa8 _signalEventSync + 216 (CFStream.c:626) 3 CoreFoundation 0x0000000189d01e30 ___signalEventQueue_block_invoke + 28 (CFStream.c:646) 4 libdispatch.dylib 0x0000000191948370 _dispatch_call_block_and_release + 32 (init.c:1549) 5 libdispatch.dylib 0x000000019194a0d0 _dispatch_client_callout + 20 (object.m:576) 6 libdispatch.dylib 0x00000001919516d8 _dispatch_lane_serial_drain + 744 (queue.c:3934) 7 libdispatch.dylib 0x00000001919521e0 _dispatch_lane_invoke + 380 (queue.c:4025) 8 libdispatch.dylib 0x000000019195d258 _dispatch_root_queue_drain_deferred_wlh + 288 (queue.c:7193) 9 libdispatch.dylib 0x000000019195caa4 _dispatch_workloop_worker_thread + 540 (queue.c:6787) 10 libsystem_pthread.dylib 0x000000021214bc7c _pthread_wqthread + 288 (pthread.c:2696) 11 libsystem_pthread.dylib 0x0000000212148488 start_wqthread + 8 Crash Trace 3: 0 libobjc.A.dylib 0x00000001941d9ce8 objc_loadWeakRetained + 156 (NSObject.mm:525) 1 CoreFoundation 0x0000000196d0a0f4 _outputStreamCallbackFunc + 36 (CFObject.m:1960) 2 CoreFoundation 0x0000000196d09724 _signalEventSync + 216 (CFStream.c:626) 3 CoreFoundation 0x0000000196d07948 ___signalEventQueue_block_invoke + 28 (CFStream.c:646) 4 libdispatch.dylib 0x000000019e9de248 _dispatch_call_block_and_release + 32 (init.c:1549) 5 libdispatch.dylib 0x000000019e9dffa8 _dispatch_client_callout + 20 (object.m:576) 6 libdispatch.dylib 0x000000019e9e75cc _dispatch_lane_serial_drain + 768 (queue.c:3934) 7 libdispatch.dylib 0x000000019e9e8124 _dispatch_lane_invoke + 380 (queue.c:4025) 8 libdispatch.dylib 0x000000019e9f338c _dispatch_root_queue_drain_deferred_wlh + 288 (queue.c:7193) 9 libdispatch.dylib 0x000000019e9f2bd8 _dispatch_workloop_worker_thread + 540 (queue.c:6787) 10 libsystem_pthread.dylib 0x00000002220f3680 _pthread_wqthread + 288 (pthread.c:2696) 11 libsystem_pthread.dylib 0x00000002220f1474 start_wqthread + 8 Notable Points: All crashes occur only on iOS 18 and newer versions. The crashes are independent of the Xcode version used to build the app (tested with both Xcode 15.4 and 16). All crash traces occur in CoreFoundation and seem to have nothing related to our app codebase. I've attempted to profile the app using Instruments to identify any zombie objects, but the crashes do not manifest on my own devices. I've referred to discussions, including this forum thread, but have not yet found a solution. Questions: Has anyone else encountered similar issues on iOS 18? Are there specific aspects of iOS 18 that might contribute to these CoreFoundation and libobjc-related crashes? Would appreciate any suggestions for further diagnostics or potential workarounds. Thank you for your help!
0
0
40
18h
Starting iOS & iPadOS App Development: Seeking Guidance and Learning Path
I am basically a front-end engineer and am eager to transition into app development, particularly for iOS and iPadOS platforms. I am aware of tools like Xcode and Swift but would greatly appreciate guidance on the best place to start. Please suggest a structured learning path or resources that would help me build a strong foundation and advance my skills effectively? Thank you!
0
0
31
19h
On-Device Website Filtering Without VPN/Root Certificates
Hi everyone, Our app helps users block adult websites to promote focus and digital wellness. During the App Store review, it was flagged under Guideline 2.5.1 for using a VPN profile to block content, with Apple advising us to remove this feature. Since blocking adult content is core to our app, we’re looking for compliant alternatives: Can Network Extensions Framework (e.g., NEDNSProxyProvider) be used for on-device filtering? Would pre-configured safe DNS (e.g., CleanBrowsing) be acceptable? Are there compliant examples of similar apps? Any advice on achieving this functionality within Apple’s guidelines would be greatly appreciated. Thanks!
1
0
80
21h
RunLoop behaviour change with performBlock?
I have a dedicated render thread with a run loop that has a CADisplayLink added to it (that's the only input source attached). The render thread has this loop in it: while (_continueRunLoop) { [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } I have some code to stop the render thread that sets _continueRunLoop to false in a block, and then does a pthread_join on the render thread: [_renderThreadRunLoop performBlock:^{ self->_continueRunLoop = NO; }]; pthread_join(_renderThread, NULL); I have noticed recently (iOS 18?) that if the Display Link is paused or invalidated before trying to stop the loop then the pthread_join blocks forever and the render thread is still sitting in the runMode:beforeDate: method. If the display link is still active then it does exit the loop, but only after one more turn of the display link callback. The most likely explanation I can think of is there has been a behaviour change to performBlock - I believe this used to "consume" a turn of the run loop, and exit the runMode:beforeDate call but now it happens without leaving that function. I can't find specific mention in the docs of the expected behaviour for performBlock - just that other RunLoop input sources cause the run method to exit, and timer sources do not. Is it possible that the behaviour has changed here?
4
0
91
1d
UserDefaults.standard.set() shows warning, but it can not be acted upon?
We run simple iOS Swift code triggered by a remote notification: UserDefaults.standard.set("key", forKey: "value") It runs fine when the app is active or inactive, but when the device is closed/locked and the code is triggered, we see a warning in Xcode: Couldn't write values for keys ( key ) in CFPrefsPlistSource<0x3018802d0> (Domain: com.example, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: No): Path not accessible Not updating lastKnownShmemState in CFPrefsPlistSource<0x3018802d0> (Domain: com.example, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: No): 767 -> 767 The issue is that there seems to be no way to catch that warning. The value is set, when it's re-read the value is correct. But the value is never written to disk, so after an app restart/update the value is gone, potentially has an old wrong value. This code runs without any interruption, it's just showing the warning on iOS 17.7.1 on iPad: UserDefaults.standard.set("key", forKey: "value") UserDefaults.standard.synchronize() print("value: \(UserDefaults.standard.string(forKey: "key"))") Should there not be a way to catch this, so the code can act accordingly to the circumstances? It would be good to know inside the code that the value is not persisted. I would expect that an exception is generated somewhere which can be caught. It seems .completeFileProtectionUntilFirstUserAuthentication enables files to be written to disk while the device is closed/locked, can something similar be used for UserDefaults.standard?
1
0
99
2d
Is there documentation for the Swift KVO method `observe(_:options:changeHandler:)`?
I can't seem to find much documentation on the observe(_:options:changeHandler:) method itself. There is this page which has some example use, but there is no link to a 'real' documentation page for the method. Additionally the 'quick help' has a little bit of info, but no parameter definitions or explanation of if/how the return value or changeHandler closure are retained.
4
0
139
6d
macOS 15.2, strange runtime error on NSDictionary extension method
We are developing remote desktop app on macOS and recently got user's report about unexpected app crash on macOS 15.2 beta. On macOS 15.2, there's strange app crash on NSDictionary extension method. We have narrowed down the steps and create the sample code to duplicate this issue. Create a cocoa app project in objective-c Try to access [NSNull null] value in NSDictionary Use specific method name for NSDictionary extension - (long long)longLongValueForKey:(NSString*)key withDefault:(long long)defaultValue; The console output for the example app is like below, the method pointer seems to be wrong when trying to get value with longLongValueForKey:withDefault: method to a [NSNull null] object. ********* longLongValueForKey: a: 0 ********* longLongValueForKey: b: 100 ********* longLongValueForKey: c: 0 ********* longLongValueForKey:withDefault: a: -1 ********* longLongValueForKey:withDefault: b: 100 ********* exception: -[NSNull longLongValue]: unrecognized selector sent to instance 0x7ff8528d9760 ********* longLongValueForKey:withDefault1: a: -1 ********* longLongValueForKey:withDefault1: b: 100 ********* longLongValueForKey:withDefault1: c: -1 Please create an objective-c app project and add below code to reproduce this issue. // // AppDelegate.m // DictionaryTest // // Created by splashtop on 2024/11/13. // #import "AppDelegate.h" #define IsNullObject(id) ((!id) || [id isKindOfClass:[NSNull class]]) @interface NSDictionary (extension) (long long)longLongValueForKey:(NSString*)key; (long long)longLongValueForKey:(NSString*)key withDefault:(long long)defaultValue; (long long)longLongValueForKey:(NSString*)key withDefault1:(long long)defaultValue; @end @interface AppDelegate () @property (strong) IBOutlet NSWindow *window; @end @implementation AppDelegate (void)applicationDidFinishLaunching:(NSNotification *)aNotification { // Insert code here to initialize your application NSDictionary* dict = @{ @"b" : @(100), @"c" : [NSNull null], }; @try { long long a = [dict longLongValueForKey:@"a"]; NSLog(@"********* longLongValueForKey: a: %lld", a); long long b = [dict longLongValueForKey:@"b"]; NSLog(@"********* longLongValueForKey: b: %lld", b); long long c = [dict longLongValueForKey:@"c"]; NSLog(@"********* longLongValueForKey: c: %lld", c); } @catch(NSException* e) { NSLog(@"********* exception: %@", e); } @try { long long a = [dict longLongValueForKey:@"a" withDefault:-1]; NSLog(@"********* longLongValueForKey:withDefault: a: %lld", a); long long b = [dict longLongValueForKey:@"b" withDefault:-1]; NSLog(@"********* longLongValueForKey:withDefault: b: %lld", b); long long c = [dict longLongValueForKey:@"c" withDefault:-1]; NSLog(@"********* longLongValueForKey:withDefault: c: %lld", c); } @catch(NSException* e) { NSLog(@"********* exception: %@", e); } @try { long long a = [dict longLongValueForKey:@"a" withDefault1:-1]; NSLog(@"********* longLongValueForKey:withDefault1: a: %lld", a); long long b = [dict longLongValueForKey:@"b" withDefault1:-1]; NSLog(@"********* longLongValueForKey:withDefault1: b: %lld", b); long long c = [dict longLongValueForKey:@"c" withDefault1:-1]; NSLog(@"********* longLongValueForKey:withDefault1: c: %lld", c); } @catch(NSException* e) { NSLog(@"********* exception: %@", e); } } @end @implementation NSDictionary (extension) (long long)longLongValueForKey:(NSString*)key { long long defaultValue = 0; id value = [self objectForKey:key]; if (IsNullObject(value) || value == [NSNull null]) { return defaultValue; } if ([value isKindOfClass:[NSNumber class]] || [value isKindOfClass:[NSString class]]) { return [value longLongValue]; } return defaultValue; } (long long)longLongValueForKey:(NSString*)key withDefault:(long long)defaultValue { id value = [self objectForKey:key]; if (IsNullObject(value) || value == [NSNull null]) { return defaultValue; } if ([value isKindOfClass:[NSNumber class]] || [value isKindOfClass:[NSString class]]) { return [value longLongValue]; } return defaultValue; } (long long)longLongValueForKey:(NSString*)key withDefault1:(long long)defaultValue { id value = [self objectForKey:key]; if (IsNullObject(value) || value == [NSNull null]) { return defaultValue; } if ([value isKindOfClass:[NSNumber class]] || [value isKindOfClass:[NSString class]]) { return [value longLongValue]; } return defaultValue; } @end
1
0
81
6d
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}}}}}
1
0
79
1w
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
189
1w
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
188
2w
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
113
2w
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!
4
0
165
1w
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?
4
2
203
1w
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
208
2w
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
191
4w
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
273
4w