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.

Pinned Posts

Posts under Foundation tag

338 Posts
Sort by:
Post not yet marked as solved
0 Replies
43 Views
Over the years I’ve helped a lot of folks investigate a lot of crashes. In some cases those crashes only make sense if you know a little about how Foundation and Core Foundation types are toll-free bridged. This post is my attempt to explain that. If you have questions or comments, please put them in a new thread. Tag it with Foundation and Debugging so that I see it. Share and Enjoy — Quinn “The Eskimo!” @ Devel oper Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" Crashes on the Toll-Free Bridge Certain Core Foundation (CF) types are toll-free bridged to their Foundation equivalent. That allows you to pass the Foundation object to a CF routine and vice versa [1]. For example, NSData and CFData are toll-free bridged, allowing you to pass an NSData object to a CF routine like CFDataGetBytePtr. For more information on this topic, see Toll-Free Bridged Types within Core Foundation Design Concepts in the Documentation Archive. This is cool, but it does present some interesting challenges. One of these relates to subclassing. Many of the toll-free bridge Foundation types support subclassing and, if you create a instance of your subclass and pass it to CF, CF has to do the right thing. Continuing the NSData example above, it’s legal [2] to create your own subclass of NSData with a completely custom implementation. As long as you implement the -bytes method and the length property, all the other NSData methods will just work. Moreover, this class works with CFData routines as well. If you pass an instance of your subclass to CFDataGetBytePtr, CF detects that it’s an Objective-C object and calls your -bytes method. Exciting! So, how does this actually work? It relies on the fact that CF and Objective-C types share a common object header. That object header is an implementation detail, but the first word of the header is always an indication of the class [3]. CF uses this word to distinguish between CF and Objective-C objects. Note This basic technique is used by other Objective-C compatible types, including Swift objects and XPC objects. If, for example, you call CFRetain on Swift object, it detects that this is an Objective-C compatible object and calls objc_retain, which in turns detects that this is a Swift object and calls swift_retain. To see this in action, check out the Swift Foundation open source. Continuing our NSData example, the first line of CFDataGetBytePtr uses the CF_OBJC_FUNCDISPATCHV macro to check if this is an Objective-C object and, if so, call -bytes on it. Sadly, the open source trail goes cold here, because Objective-C integration is only supported on Apple platforms. However, some disassembly reveals the presence of an internal routine called CF_IS_OBJC. (lldb) disas -n CFDataGetBytePtr CoreFoundation`CFDataGetBytePtr: … <+0>: pacibsp … <+4>: stp x20, x19, [sp, #-0x20]! … <+8>: stp x29, x30, [sp, #0x10] … <+12>: add x29, sp, #0x10 … <+16>: mov x19, x0 … <+20>: mov w0, #0x14 … <+24>: mov x1, x19 … <+28>: bl 0x19cc60100 ; CF_IS_OBJC … WARNING Do not rely on the presence or behaviour of CF_IS_OBJC. This is an implementation detail. It has changed many times in the past and may well change in the future [4]. While this is an implementation detail, it’s useful to know about when debugging. If you pass something that’s not a valid object to CFDataGetBytePtr, you might see it crash in CF_IS_OBJC. For example, this code: void test(void) { struct { int i; } s = { 0 }; CFDataGetBytePtr( (const struct __CFData *) &s ); } crashes like this: Exception Type: EXC_BREAKPOINT (SIGTRAP) … Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 CoreFoundation … CF_IS_OBJC + 76 1 CoreFoundation … CFDataGetBytePtr + 32 2 xxot … test + 24 … … In this case CF_IS_OBJC has detected the problem and trapped, resulting in an EXC_BREAKPOINT crash. However, if you pass it a pointer that looks more like an object, this might crash trying to dereference a bad pointer, which will result in a EXC_BAD_ACCESS crash. The other common failure you see occurs when you pass it an Objective-C object of the wrong type. Consider code like this: void test(void) { id str = [NSString stringWithFormat:@"Hello Cruel World!-%d", (int) getpid()]; const void * ptr = CFDataGetBytePtr( (__bridge CFDataRef) str); … } When you run this code, it throws a language exception like this: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString bytes]: unrecognized selector sent to instance 0x6000028545a0' *** First throw call stack: ( 0 CoreFoundation … __exceptionPreprocess + 176 1 libobjc.A.dylib … objc_exception_throw + 60 2 CoreFoundation … -[NSObject(NSObject) __retain_OA] + 0 3 CoreFoundation … ___forwarding___ + 1580 4 CoreFoundation … _CF_forwarding_prep_0 + 96 5 xxot … test + 92 … ) CFDataGetBytePtr has detected this is an Objective-C object and called -bytes on it. However, this is actually an NSString [5] and NSString doesn’t implement the -bytes method. The end result is an unrecognized selector exception. [1] To be clear, when using CF objects in Objective-C you first cast the CF object to its Foundation equivalent and then call Objective-C methods on it. [2] While it’s legal to do this, it’s probably not very sensible. Subclassing Foundation types is something that might’ve made sense back in the day, but these days there are generally better ways to solve your problems. [3] Historically this word was called isa and was of type Class, that is, a pointer to the actual Objective-C class. These days things are much more complex (-: [4] Historically, CF_IS_OBJC was very simple: If the object’s isa word was 0, it was a CF object, otherwise it was an Objective-C object. That’s no longer the case. [5] The actual type is __NSCFString. That’s because NSString is a class cluster. For more about that, see Class Clusters within Cocoa Fundamentals Guide in the Documentation Archive.
Posted
by
Post not yet marked as solved
0 Replies
55 Views
My app is using iBeacons, and I am using func startMonitoring(for region: CLRegion). Then I am using func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) and func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) to run logic when user enters / exits certain Beacon CLBeaconRegion. Everything worked fine until recently, iOS 17 update I guess. Now after I call startMonitoring(for: region) the code works for couple hours, and then it seems my app is somehow suspended and no longer able to use CoreLocation, and my code does not work, entry and exit events to beacon regions are NOT detected. Funny enough I have some Beacon managment apps that can scan for nearby beacons, when I run one of those apps, I see on top of iPhone screen “hollow arrow” sign that marks CoreLocation being used, and then my app works for few minutes, and then again my app is suspended, and no entry/exit events into beacon regions are detected. I could figure out how to engage CoreLocation but that would rely on user intentionally opening my app, and the sole purpose of my app is to remind user when he is near one of his Beacons, so expecting user to remember to open my app defeats my apps purpose. I added Location Updates under Background Modes for my app , maybe my app has little bit more background time until it is suspended, but the problem still persists. So for any Beacon based app to work it should be able to monitor for nearby beacons, and run logic once beacons are detected. Any suggestions on how I could solve this? iOS 17 CLMonitor has BeaconIdentityCondition that can match UUID, major, minor but this is only to detect we are NEAR a Beacon (entry event), what about exit event? Should I monitor for a change in Condition from .satisfied to .unsatisfied and that transition is Exit event? My questions: Is there a way to use old code: startMonitoring(for: region) - how to fix my app so it DOES NOT get suspended, and so that this method can monitor for beacons in background with AlwaysAllow authorization? If not and I must switch to CLMonitor how do I capture Exit event - when user exits Beacon region in iOS 17 using CLMonitor? Thanks
Posted
by
Post not yet marked as solved
2 Replies
71 Views
I have an Electron app on macOS Sonoma (Intel arch). It has a native addon (app.node) using node-addon-api. Recently it crashed, with the stack trace (given below). What is the CF_IS_OBJC function inside the CFDataGetBytePtr function, and why did it crash there? [NSEvent addGlobalMonitorForEventsMatchingMask:NSEventMaskKeyDown handler:^(NSEvent *event) { // code using CFDataGetBytePtr function }]; [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyDown handler:^NSEvent *_Nullable(NSEvent *event) { // code using CFDataGetBytePtr function return event; }]; I have key events monitors attached using addGlobalMonitorForEventsMatchingMask and addLocalMonitorForEventsMatchingMask in my native code and they use the CFDataGetBytePtr function there. So I think the issue happened in the key event monitor handler when calling the CFDataGetBytePtr function because my native addon app.node is also present in the trace. Also from the third and fourth entry in the stack trace, it seems like it happened while the app was updating. OS Version: macOS 14.4 (23E214) Report Version: 104 Crashed Thread: 5490 Application Specific Information: Fatal Error: EXC_BAD_ACCESS / KERN_INVALID_ADDRESS / 0x0 Thread 5490 Crashed: 0 CoreFoundation 0x19c970118 CF_IS_OBJC 1 CoreFoundation 0x19c83b280 CFDataGetBytePtr 2 .app.desktop.1inmRz 0x104a5bec0 &lt;unknown&gt; 3 .app.desktop.1inmRz 0x104a57b28 &lt;unknown&gt; 4 app.node 0x104a80a7c [inlined] Napi::details::CallbackData&lt;T&gt;::Wrapper::lambda::operator() (napi-inl.h:117) 5 app.node 0x104a80a7c Napi::details::WrapCallback&lt;T&gt; (napi-inl.h:79) 6 app.node 0x104a80a24 Napi::details::CallbackData&lt;T&gt;::Wrapper (napi-inl.h:112) 7 Electron Framework 0x11472e5e0 v8impl::(anonymous namespace)::FunctionCallbackWrapper::Invoke (js_native_api_v8.cc:441) 8 &lt;unknown&gt; 0x147e105f8 &lt;unknown&gt; 9 &lt;unknown&gt; 0x1401d0814 &lt;unknown&gt; 10 &lt;unknown&gt; 0x1401d0a9c &lt;unknown&gt; 11 &lt;unknown&gt; 0x147f19368 &lt;unknown&gt; 12 &lt;unknown&gt; 0x147e0aab0 &lt;unknown&gt; 13 &lt;unknown&gt; 0x1401d0e00 &lt;unknown&gt; 14 &lt;unknown&gt; 0x1401d1ac0 &lt;unknown&gt; 15 &lt;unknown&gt; 0x147f19368 &lt;unknown&gt; 16 &lt;unknown&gt; 0x147e0aab0 &lt;unknown&gt; 17 &lt;unknown&gt; 0x1401d1494 &lt;unknown&gt; 18 &lt;unknown&gt; 0x1401d20dc &lt;unknown&gt; 19 &lt;unknown&gt; 0x147e4c1b4 &lt;unknown&gt; 20 &lt;unknown&gt; 0x147f1b5f8 &lt;unknown&gt; 21 &lt;unknown&gt; 0x147e3b754 &lt;unknown&gt; 22 &lt;unknown&gt; 0x147e0b618 &lt;unknown&gt; 23 Electron Framework 0x10ee0c49c v8::internal::(anonymous namespace)::Invoke (simulator.h:178) 24 Electron Framework 0x10ee0d08c v8::internal::(anonymous namespace)::InvokeWithTryCatch (execution.cc:475) 25 Electron Framework 0x10ee0d1e0 v8::internal::Execution::TryRunMicrotasks (execution.cc:576) 26 Electron Framework 0x10ee37364 v8::internal::MicrotaskQueue::PerformCheckpoint (microtask-queue.cc:176) 27 Electron Framework 0x1146cce9c node::InternalCallbackScope::Close (callback.cc:137) 28 Electron Framework 0x1146ccb64 node::InternalCallbackScope::~InternalCallbackScope (callback.cc:92) 29 Electron Framework 0x1147112b4 node::Environment::RunTimers (env.cc:1376) 30 Electron Framework 0x10daf9980 uv__run_timers (timer.c:178) 31 Electron Framework 0x10dafcb3c uv_run (core.c:465) 32 Electron Framework 0x10dc944d4 electron::NodeBindings::UvRunOnce (node_bindings.cc:891) 33 Electron Framework 0x110e2016c base::TaskAnnotator::RunTaskImpl (callback.h:156) 34 Electron Framework 0x110e3cea4 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork (task_annotator.h:89) 35 Electron Framework 0x110e8851c base::MessagePumpCFRunLoopBase::RunWorkSource (message_pump_apple.mm:444) 36 Electron Framework 0x10da7ad7c base::apple::CallWithEHFrame 37 Electron Framework 0x110e876a4 base::MessagePumpCFRunLoopBase::RunWorkSource (message_pump_apple.mm:415) 38 CoreFoundation 0x19c89deac __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ 39 CoreFoundation 0x19c89de40 __CFRunLoopDoSource0 40 CoreFoundation 0x19c89dbb0 __CFRunLoopDoSources0 41 CoreFoundation 0x19c89c79c __CFRunLoopRun 42 CoreFoundation 0x19c89be08 CFRunLoopRunSpecific 43 HIToolbox 0x1a7036ffc RunCurrentEventLoopInMode 44 HIToolbox 0x1a7036e38 ReceiveNextEventCommon 45 HIToolbox 0x1a7036b90 _BlockUntilNextEventMatchingListInModeWithFilter 46 AppKit 0x1a00f496c _DPSNextEvent 47 AppKit 0x1a08e6de8 -[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] 48 AppKit 0x1a00e7cb4 -[NSApplication run] 49 Electron Framework 0x110e89244 base::MessagePumpNSApplication::DoRun (message_pump_apple.mm:805) 50 Electron Framework 0x110e87068 base::MessagePumpCFRunLoopBase::Run (message_pump_apple.mm:156) 51 Electron Framework 0x110e3d9a0 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run (thread_controller_with_message_pump_impl.cc:646) 52 Electron Framework 0x110e05a98 base::RunLoop::Run (run_loop.cc:134) 53 Electron Framework 0x10ffcbcd0 content::BrowserMainLoop::RunMainMessageLoop (browser_main_loop.cc:1094) 54 Electron Framework 0x10ffcd744 content::BrowserMainRunnerImpl::Run (browser_main_runner_impl.cc:158) 55 Electron Framework 0x10ffc964c content::BrowserMain (browser_main.cc:34) 56 Electron Framework 0x10de12aa8 content::RunBrowserProcessMain (content_main_runner_impl.cc:712) 57 Electron Framework 0x10de13b1c content::ContentMainRunnerImpl::RunBrowser (content_main_runner_impl.cc:1299) ...
Posted
by
Post not yet marked as solved
1 Replies
75 Views
When following this guide https://developer.apple.com/documentation/xcode/embedding-a-helper-tool-in-a-sandboxed-app I cannot run the embedded binary. I'm getting this error: "zsh: trace trap" I would like to be able to use the embedded binary for NativeMessaging with for example Chrome but I can't figure out how to allow it to be executable even with sandboxing enabled. How are Strongbox able to do this with their afproxy executable?
Posted
by
Post not yet marked as solved
1 Replies
154 Views
Hi all, I am working on macOS 14.4.1 and I am having an issue with the Desktop Spaces feature. Calling defaults read com.apple.spaces.plist gives me a list of all current spaces, which reports the existence of a phantom Space that cannot be seen nor interacted with. The ID of that Space leads me to the following: which shows that space 23 is associated with the Dashboard feature, that does not exist in Sonoma! I have tried to: restart the computer, forcefully disable the dashboard with defaults write com.apple.dashboard mcx-disabled -boolean YES killall Dock Neither attempt erased the phantom Space, which creates conflicts in my setup. I have tried completely disabling Widgets in the Preferences, closing all apps, deleting every space (including the "current" one, by creating a new one to substitute it) and restarting the Mac. After this, the id of the dashboard space changed: but it is still there. I do not know which step changed its id, because to my knowledge the com.apple.spaces.plist file takes a while to be updated (https://apple.stackexchange.com/questions/388449). But no hints on how to erase it. The specific issues I am having are that this phantom space prevents any software that reads the Spaces state, to save it, from working correctly (e.g. DisplayMaid, Workspaces). In particular, I am now developing a Hammerspoon (https://www.hammerspoon.org/) module to do just that, to set it precisely to my liking: https://github.com/tplobo/restore-spaces. Listing the spaces to cycle through them always reports this phantom space, and since it cannot be identified as the "non-existing" one (up until the time it breaks one of the Lua commands that manage spaces), I am unable to exclude it somehow to continue development. Is there a command to restart the Spaces feature, to completely erase all spaces and check if this removes this phantom Space? Otherwise, any alternative suggestions? I have already posted this in the standard forum, but no luck there. Thank you,
Posted
by
Post not yet marked as solved
1 Replies
153 Views
Is the timeout for session-level authentication challenge handling documented somewhere? For example, if I get the urlSession(_:didReceive:) callback for server trust authentication, how long do I have to invoke the completion handler (or return from the callback if using Swift Concurrency)? Or is this completely dependent on the server's settings?
Posted
by
Post not yet marked as solved
1 Replies
108 Views
Hello! Recently, the following crash issue began to occur. 0 libswiftCore.dylib 0x000000019ffaa3c8 closure #1 in closure #1 in closure #1 in _assertionFailure+ 238536 (_:_:file:line:flags:) + 228 1 libswiftCore.dylib 0x000000019ffaa2a0 closure #1 in closure #1 in _assertionFailure+ 238240 (_:_:file:line:flags:) + 332 2 libswiftCore.dylib 0x000000019ffa9c2c _assertionFailure+ 236588 (_:_:file:line:flags:) + 184 3 libswiftCore.dylib 0x000000019ffac4fc specialized BidirectionalCollection._index+ 247036 (_:offsetBy:) + 1280 4 libswiftCore.dylib 0x00000001a016d630 String.UTF16View._indexRange+ 2086448 (for:from:) + 184 5 libswiftCore.dylib 0x00000001a018561c __StringStorage.getCharacters+ 2184732 (_:range:) + 112 6 libswiftCore.dylib 0x00000001a0185720 @objc __StringStorage.getCharacters+ 2184992 (_:range:) + 36 7 CoreFoundation 0x00000001a16893e0 __CFStringEncodeByteStream + 1864 8 Foundation 0x00000001a0527c94 -[NSString+ 208020 (NSStringOtherEncodings) getBytes:maxLength:usedLength:encoding:options:range:remainingRange:] + 260 ... It seems like assert is being called. Can you tell me a case that could be the cause? Also, this is a code I have been using for a long time, but recently it started crashing. Have there been any internal changes recently? Please understand that the entire crash log cannot be attached for security reasons. Any help would be greatly appreciated!
Posted
by
Post not yet marked as solved
2 Replies
162 Views
I have tried to insert 1L key-values into the user defaults. It is working fine until 50k key-values. After some time, am getting Not updating lastKnownShmemState in CFPrefsPlistSource<0x2825b0c60> (Domain: peformance_validator, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: No) also, key-values are not updating in the plist as well. peformance_validator is my user defaults group name. How can I solve this ?
Posted
by
Post not yet marked as solved
1 Replies
127 Views
NSString *jsonString = @"{\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":\"value3\",\"key4\":\"value4\"}"; NSString *jsonString2 = @"{\"key2\":\"value2\",\"key1\":\"value1\",\"key4\":\"value4\",\"key3\":\"value3\"}"; NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSData *jsonData2 = [jsonString2 dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *dict1 = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil]; NSDictionary *dict2 = [NSJSONSerialization JSONObjectWithData:jsonData2 options:NSJSONReadingMutableContainers error:nil]; The expected results are: dict1:key1,key2,key3,key4 dict2:key2,key1,key4,key3 Is there any way to make that happen?
Posted
by
Post not yet marked as solved
1 Replies
113 Views
Hi, I am having this rare issues, where a handful of my users are crashing when trying to access their realm file. This is the error I'm seeing: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=3 "Failed to open file at path '/var/mobile/Containers/Data/Application/BCA5E4BC-5923-4D7E-8142-AB49B32A7E59/Documents/default.realm.lock': Operation not permitted" UserInfo={Error Code=3, NSFilePath=/var/mobile/Containers/Data/Application/BCA5E4BC-5923-4D7E-8142-AB49B32A7E59/Documents/default.realm.lock, Error Name=PermissionDenied, NSLocalizedDescription=Failed to open file at path '/var/mobile/Containers/Data/Application/BCA5E4BC-5923-4D7E-8142-AB49B32A7E59/Documents/default.realm.lock': Operation not permitted} and I can report that for all for those users, it seems that identiferForVendor has returned nil. So it looks like that's the common denominator. Any idea on what other data I can log or what's the issue here? Thanks..!
Posted
by
Post not yet marked as solved
1 Replies
177 Views
I have a customer who wants to protect the REST API of their app with a private certificate. They would then distribute the client certificate to the authorized users. Their app would not work unless the client certificate is already installed on the user's phone before they run the app. I have never done this before. Is it possible to install a client certificate on an iPhone without running an app, for example if it were sent in an email message? And if it is possible, is App Review going to let such an app into the app store? Thanks, Frank
Posted
by
Post not yet marked as solved
1 Replies
167 Views
Hi I Download my app from test flight, when i click submit button to a backend call. App expects to get back with the response from the backend, to take to next pages. But the app seems to be stuck waiting for the backend response. No error messages seen. i am sure the backend call is blocked from the test flight version. Same code works well from emulator and the physical device from local and from Google PlayStore. Only the test flight is the problem. I am sure i messed up some settings , My Info.plist has as in below, can anyone please help. NSAppTransportSecurity NSPinnedNetworkSecurityItems MyBundleName NSIncludesSubdomains NSAllowsArbitraryLoads NSPinnedCAIdentities SPKI-SHA256-BASE64 THEKEY
Posted
by
Post marked as solved
3 Replies
144 Views
I have used [[NSDistributedNotificationCenter defaultCenter] addObserver in process AA to listen notification from other process BB, It works fine. But when make the observer process AA as a launch daemon (which is started by launchd), It found below difference. If run process BB as root privilege, AA can not receive notification posted by BB. If make process BB as a launch daemon, AA can receive notification posted by BB. What was happened in above difference, It can not find any document about this, Thanks.
Posted
by
Post not yet marked as solved
2 Replies
148 Views
Xcode Version 15.0.1 (15A507) Crash log Hardware Model: iPhone14,7 Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] OS Version: iPhone OS 16.6 (20G75) Release Type: User Baseband Version: 1.80.02 Report Version: 104 Exception Type: EXC_CRASH (SIGABRT) Triggered by Thread: 26 Application Specific Information: abort() called Last Exception Backtrace: 0 CoreFoundation 0x1b3c54cb4 __exceptionPreprocess + 164 1 libobjc.A.dylib 0x1accf03d0 objc_exception_throw + 60 2 Foundation 0x1adf6950c -[NSData(NSData) _base64EncodingAsString:withOptions:] + 1072 3 Foundation 0x1ae2cf8bc Data.base64EncodedString(options:) + 640 ... 6 libdispatch.dylib 0x1bb11a320 _dispatch_call_block_and_release + 32 7 libdispatch.dylib 0x1bb11beac _dispatch_client_callout + 20 8 libdispatch.dylib 0x1bb11ef8c _dispatch_queue_override_invoke + 788 9 libdispatch.dylib 0x1bb12d944 _dispatch_root_queue_drain + 396 10 libdispatch.dylib 0x1bb12e158 _dispatch_worker_thread2 + 164 11 libsystem_pthread.dylib 0x213a85da0 _pthread_wqthread + 228 Thread 26 name: Dispatch queue: com.apple.root.default-qos Thread 26 Crashed: 0 libsystem_kernel.dylib 0x1f2c11578 __pthread_kill + 8 1 libsystem_pthread.dylib 0x213a8c118 pthread_kill + 268 2 libsystem_c.dylib 0x1bb17c178 abort + 180 3 libc++abi.dylib 0x2139cabf8 abort_message + 132 4 libc++abi.dylib 0x2139ba444 demangling_terminate_handler() + 348 5 libobjc.A.dylib 0x1accf5ea4 _objc_terminate() + 144 6 libc++abi.dylib 0x2139c9fbc std::__terminate(void (*)()) + 16 7 libc++abi.dylib 0x2139c9f60 std::terminate() + 56 8 libdispatch.dylib 0x1bb11bec0 _dispatch_client_callout + 40 9 libdispatch.dylib 0x1bb11ef8c _dispatch_queue_override_invoke + 788 10 libdispatch.dylib 0x1bb12d944 _dispatch_root_queue_drain + 396 11 libdispatch.dylib 0x1bb12e158 _dispatch_worker_thread2 + 164 12 libsystem_pthread.dylib 0x213a85da0 _pthread_wqthread + 228 13 libsystem_pthread.dylib 0x213a85b7c start_wqthread + 8 12 libsystem_pthread.dylib 0x213a85b7c start_wqthread + 8 My code private func encodeStringTo64(fromString: String) -> String? { let plainData = fromString.data(using: .utf8) return plainData?.base64EncodedString(options: []) } Call foundation method extension Data { ... /// Returns a Base-64 encoded string. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded string. @inlinable public func base64EncodedString(options: Data.Base64EncodingOptions = []) -> String } Description This foundation method don't have throws, but it throw an exception. It will cause a crash.
Posted
by
Post not yet marked as solved
1 Replies
174 Views
Im using Notions API to print out some data from one of my own pages in notion and im using URLSession to make the request then parsing the unwrapped data but nothing is being returned to my console and I know my endpoint and API key is correct. I've gone through the notion API documentation can't can't seem to find anything in it that I am not doing or doing wrong. Ill provide my code as well as the documentation I've been consulting: https://developers.notion.com/reference/intro import Foundation struct Page: Codable { let id: String let title: String } let endpoint = URL(string: "https://api.notion.com/v1/pages/8efc0ca3d9cc44fbb1f34383b794b817") let apiKey = "… redacted …" let session = URLSession.shared func makeRequest() { if let endpoint = endpoint { let task = URLSession.shared.dataTask(with: endpoint) { data, response, error in if let taskError = error { print("could not establish url request:\(taskError)") return } if let unwrapData = data { //safely unwrapping the data value using if let do { let decoder = JSONDecoder() //JSONDecoder method to decode api data, let codeUnwrappedData = try decoder.decode(Page.self,from: unwrapData) //type: specifies its a struct, from: passes the data parmeter that contains the api data to be decoded } catch { print("could not parse json data") } } if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 200 { if let apiData = data { print(String(data: apiData, encoding: .utf8)!) } } else { print("unsuccessful http response:\(httpResponse)") } makeRequest() } } task.resume() } }
Posted
by
Post not yet marked as solved
2 Replies
184 Views
It seems that the first time I open my app after the phone is restarted, the app does not properly access UserDefaults. When my app is launched, I pull relevant user settings / preferences from UserDefaults. I recently noticed (after some users reached out about issues) that the first time the app is opened after a restart, the app appears as though all user settings / preferences have been erased. If the app is force quit and reopened, the user data seems to come back normally. If the user takes action in the app before force quitting, though, UserDefaults will be written to with these new, empty values (essentially erasing what used to be in UserDefaults). This makes it seem as though right after the phone is restarted, the app is unable to pull data from UserDefaults for some reason. Has anyone else seen this issue? It could also be due to the lifecycle of my app and how I access UserDefaults, so if others don't have this issue it would be great to hear how you handle this.
Posted
by
Post marked as solved
2 Replies
232 Views
My app always crash when I trying to assign an enum to a value of[String: Any] only on iOS14.6, tested on iOS15, iOS16, iOS17, never saw this issue. The function would pass an ConnectState enum and a serial number string to a userInfo of notification, received class may perform some UI updates when connect state changed. func post(state: ConnectState, serial: Int) { var userInfo: [String: Any] = [:] userInfo["state"] = state userInfo["serial"] = serial print(userInfo) NotificationCenter.default.post(name: NSNotification.Name("PostName"), object: nil, userInfo: userInfo) } @objc enum ConnectState: UInt8 { case connected = 0x00 case disConnected = 0x01 var description: String { switch self { case .connected: return "connected" case .disConnected: return "disConnected" } } } Classes received this notification, may perform some task based on connect state changed. class AClass { init() { NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: NSNotification.Name("PostName"), object: nil) } @objc func handleNotification(_ notification :Notification) { let state = notification.userInfo?["state"] as! ConnectState print("AClass handleNotification: \(state.description)") } } let a = AClass() post(state: .disConnected, serial: 123456) post(state: .connected, serial: 123456) //["serial": 123456, "state": __lldb_expr_3.ConnectState] //AClass handleNotification: disConnected //["serial": 123456, "state": __lldb_expr_3.ConnectState] //AClass handleNotification: connected The crashes always happened in the line that assigning the ConnectState enum to dictionary [String: Any] value, both connect state and serialNumber are not nil or optional. I'm not sure why would this related to a allocate issue, is my code wrong? AppName(645,0x16f61f000) malloc: can't allocate region :*** mach_vm_map(size=1152921504606863360, flags: 100) failed (error code=3) AppName(645,0x16f61f000) malloc: *** set a breakpoint in malloc_error_break to debug ```Since we only have one iOS14.6 device, it will be a challenge to test on other same iOS version device, nor test on simulator.
Posted
by
Post marked as solved
6 Replies
217 Views
Hi together, i have truble to parse an json with an array like following: "data": [ [ 0000000000, [ { "count": 0 } ] ], [ 0000000000, [ { "count": 0 } ] ] ], Can someone help me to parse that with the this? Thanks
Posted
by
Post marked as solved
2 Replies
220 Views
I have a repeating timer installed like this: _cmdTimer = [NSTimer timerWithTimeInterval: 0.5 target: self selector: @selector(timedTask:) userInfo: nil repeats: YES]; [NSRunLoop.mainRunLoop addTimer: _cmdTimer forMode: NSModalPanelRunLoopMode]; [NSRunLoop.mainRunLoop addTimer: _cmdTimer forMode: NSDefaultRunLoopMode]; The first time the timer fires, it opens a modal dialog. But then the timer does not fire again until the dialog is closed. I don't get that, since I scheduled the timer in NSModalPanelRunLoopMode. To verify that the dialog was running in that mode, just before opening the dialog I said [self performSelector: @selector(testMe) withObject: nil afterDelay: 0.7 inModes: @[NSModalPanelRunLoopMode] ]; and the testMe method did get executed while the dialog was open.
Posted
by