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

The operation couldn’t be completed. (NSURLErrorDomain error -1011.)
I'm using Firebase Auth and Firestore on my app. When I already signed in, my code in init() function workes fine and my screens automatically updated when data load. But when I first sign in, I get The operation couldn’t be completed. (NSURLErrorDomain error -1011.) error and the rest of the code dont work as it should be. What is the issue and how can I solve it?
1
0
783
Mar ’24
Behavior change for malloc zones in macOS Ventura
In our codebase we have an option in our Debug builds to replace the malloc implementation with a wrapper function so we can write unit tests to detect allocations in code we expect to be allocation free. We were doing this using malloc_default_zone() to get the malloc zone and then vm_protect to make the zone read/write to change malloc and free to wrapper functions (then restore the permissions on the zone with vm_protect. We noticed this was no longer working on macOS Ventura. When trying to research this I couldn't find anything related in the change logs but did find this StackOverflow post suggesting to use malloc_get_all_zones() instead of malloc_default_zone(). We tried this and still were not able to override the malloc behavior. In the example program below I would expect to see some MY MALLOC! message printed when malloc is called: #include <array> #include <cstdint> #include <iostream> #include <mach/mach.h> #include <malloc/malloc.h> using malloc_ptr = void *(*)(malloc_zone_t *zone, size_t size); std::array<malloc_ptr, 3> original_mallocs; template <size_t N> void *my_malloc(malloc_zone_t *zone, size_t size) { std::cout << "MY MALLOC! " << N << '\n'; return original_mallocs[N](zone, size); } template <size_t N> void hook_malloc(auto zone) { original_mallocs[N] = zone->malloc; vm_protect(mach_task_self(), (uintptr_t)zone, sizeof(malloc_zone_t), 0, VM_PROT_READ | VM_PROT_WRITE); zone->malloc = &my_malloc<N>; } void setup_malloc_hooks() { malloc_zone_t **zones = nullptr; unsigned int num_zones = 0; if (KERN_SUCCESS != malloc_get_all_zones(0, NULL, (vm_address_t **)&zones, &num_zones)) { // Reset the value in case the failure happened after it was num_zones = 0; } if (num_zones) { for (auto i = 0; i < num_zones; ++i) { switch (i) { case 0: std::cout << "hooking zone 0\n"; hook_malloc<0>(zones[0]); break; case 1: std::cout << "hooking zone 1\n"; hook_malloc<1>(zones[1]); break; case 2: std::cout << "hooking zone 2\n"; hook_malloc<2>(zones[2]); break; default: std::cout << "NOT hooking zone " << i << '\n'; break; } } } else { std::cout << "using default zone\n"; hook_malloc<0u>(malloc_default_zone()); } std::cout << '\n'; } void print_mallocs() { malloc_zone_t **zones = nullptr; unsigned int num_zones = 0; if (KERN_SUCCESS != malloc_get_all_zones(0, NULL, (vm_address_t **)&zones, &num_zones)) { // Reset the value in case the failure happened after it was num_zones = 0; } if (num_zones) { for (auto i = 0; i < num_zones; ++i) { std::cout << "zone: " << reinterpret_cast<uintptr_t>(zones[i]->malloc) << '\n'; } } else { auto zone = malloc_default_zone(); std::cout << "default zone: " << reinterpret_cast<uintptr_t>(zone->malloc) << '\n'; } std::cout << '\n'; } int main(int argc, const char *argv[]) { print_mallocs(); setup_malloc_hooks(); print_mallocs(); void *v = malloc(123); uintptr_t my_v = reinterpret_cast<uintptr_t>(v); std::cout << "my_v is " << my_v << "\n"; return 0; } Does anyone have any insight into what might have changed or how we can work around it?
1
0
464
Mar ’24
Xcode 15.3 and iOS 17.4 generate a CPU spike when launching the app
I've just updated to Xcode 15.3 and iOS 17.4 (simulator). Every time I launch the app, I see a CPU spike keeping the CPU at 100% for about 30 seconds on a background thread. After those 30 seconds, there's a 'Thread Performance Checker' error posted on the console. This does not happen when using Xcode 15.2 and running on iOS 17.2. or iOS 16.4. Thread Performance Checker: Thread running at User-initiated quality-of-service class waiting on a thread without a QoS class specified (base priority 33). Investigate ways to avoid priority inversions PID: 70633, TID: 2132693 Backtrace ================================================================= 3 CFNetwork 0x000000018454094c estimatedPropertyListSize + 28648 4 CFNetwork 0x00000001843d7fc0 cfnTranslateCFError + 1864 5 libdispatch.dylib 0x000000010557173c _dispatch_client_callout + 16 6 libdispatch.dylib 0x0000000105573210 _dispatch_once_callout + 84 7 CFNetwork 0x00000001843d7f8c cfnTranslateCFError + 1812 8 CFNetwork 0x0000000184540814 estimatedPropertyListSize + 28336 9 libdispatch.dylib 0x000000010557173c _dispatch_client_callout + 16 10 libdispatch.dylib 0x0000000105573210 _dispatch_once_callout + 84 11 CFNetwork 0x0000000184540728 estimatedPropertyListSize + 28100 12 CFNetwork 0x0000000184540794 estimatedPropertyListSize + 28208 13 libdispatch.dylib 0x000000010557173c _dispatch_client_callout + 16 14 libdispatch.dylib 0x0000000105573210 _dispatch_once_callout + 84 15 CFNetwork 0x0000000184540780 estimatedPropertyListSize + 28188 16 CFNetwork 0x00000001844e8664 _CFNetworkHTTPConnectionCacheSetLimit + 191584 17 CFNetwork 0x00000001844e78dc _CFNetworkHTTPConnectionCacheSetLimit + 188120 18 CFNetwork 0x000000018439ce5c _CFURLCachePersistMemoryToDiskNow + 25460 19 CFNetwork 0x0000000184483068 _CFStreamErrorFromCFError + 609680 20 CFNetwork 0x000000018445105c _CFStreamErrorFromCFError + 404868 21 CFNetwork 0x000000018443a040 _CFStreamErrorFromCFError + 310632 22 CFNetwork 0x000000018453be14 estimatedPropertyListSize + 9392 23 CFNetwork 0x000000018440fa5c _CFStreamErrorFromCFError + 137092 26 CFNetwork 0x000000018445b398 _CFStreamErrorFromCFError + 446656 27 CFNetwork 0x0000000184459db8 _CFStreamErrorFromCFError + 441056 28 CFNetwork 0x000000018445cf60 _CFStreamErrorFromCFError + 453768 29 CFNetwork 0x0000000184541838 estimatedPropertyListSize + 32468 30 libdispatch.dylib 0x000000010556fec4 _dispatch_call_block_and_release + 24 31 libdispatch.dylib 0x000000010557173c _dispatch_client_callout + 16 32 libdispatch.dylib 0x0000000105579a30 _dispatch_lane_serial_drain + 916 33 libdispatch.dylib 0x000000010557a774 _dispatch_lane_invoke + 420 34 libdispatch.dylib 0x000000010557b6e4 _dispatch_workloop_invoke + 864 35 libdispatch.dylib 0x00000001055871a8 _dispatch_root_queue_drain_deferred_wlh + 324 36 libdispatch.dylib 0x0000000105586604 _dispatch_workloop_worker_thread + 488 37 libsystem_pthread.dylib 0x0000000106b87924 _pthread_wqthread + 284 38 libsystem_pthread.dylib 0x0000000106b866e4 start_wqthread + 8
11
6
7.1k
Apr ’24
Time modified is reset to midnight for some files on FTP server
Every now and then I notice that the date modified of some files on my FTP server has slightly changed by setting the time to midnight. I notice this because I regularly sync the files from the FTP server to a folder on my Mac by comparing the date modified, and it happens every now and then that files that weren’t modified are listed for syncing. For many months after their creation, the time is correct and they are only synced once, but at some point the time is displayed as midnight for some reason and they are suddenly marked for syncing. The wrong time is reported both programmatically as well as in the Finder. The same files are displayed with what seems to be the correct time modified in the app Cyberduck. In this case it seems to be exactly 6 months old files. I didn't check this for the other files that this issue happened with in the past, but it could be about the same timeframe. Is this an issue with macOS? Is there a workaround? I already filed feedback FB13671336.
0
0
280
Mar ’24
Performing data network request after background uploads requests complete
I am currently implementing an upload flow that utilizes a URLSession with a background configuration to allow the upload to continue running when the application is suspended or terminated by the system. When the upload has completed, and the app is launched/woken up in the backend to respond to the upload task result, I need to make an additional data request to inform the backend that the upload has completed to trigger additional work. I am attempting to do this by making the data request and waiting for it to finish before calling the background events completion handler delivered to the AppDelegate. However, the data request never completes while in the background, but will receive a result when the app is brought to the foreground. Often the result of this data request will be a failure: Error Domain=NSURLErrorDomain Code=-997 "Lost connection to background transfer service" or Error Domain=NSURLErrorDomain Code=-999 "canceled" I understand that a URLSession with a background configuration will reject data tasks when the app is suspended or terminated. However, I am attempting to use a non-background configured network session for the data request while the application is running in the background, before the application is suspended again. Is it not possible to make additional data requests when the app is launched/woken up in the background after a background upload is completed?
1
0
399
Mar ’24
What does startaccessingsecurityscopedresource() mean for different OS?
So, I'm looking into startaccessingsecurityscopedresource() function and from my current understanding this is to get temporary access to files/folders you don't implicitly have access to i.e., that don't belong to your sandbox. I can understand what it means wrt macOS, iOS, iPadOS, but what does it mean in watchOS and tvOS where there isn't any file sharing between different apps? And what is it's relevance wrt using iCloud (if there is any?)
1
0
478
Mar ’24
Disable AutoFill option in UITextField or have control over the text which is being pasted using that option.
I have form fields in an app, I have some validations to perform like phone number should only have digits and not alphabets, however when user uses AutoFill option doing long press on textfield they have option to choose Contacts and they can tap on name and it will paste alphabets in my Phone number field, that behavior I don't want as my validations will not be fulfilled. There are no callbacks to detect and prevent that text from being pasted. In shouldChangeCharactersIn delegate method even if I return false for that paste event it ignores that and forcefully it gets pasted. Please help how to tackle such scenarios to perform above mentioned validations. Thanks
1
0
977
Mar ’24
NSAutoreleasePool issues with FFI development
I'm working on an FFI for working with ObjectiveC/Foundation/Metal. AFAIU, as many APIs create and autorelease objects, I need to ensure that an NSAutoreleasePool is active when calling into these APIs. So I've created a wrapper that basically mimics @autoreleasepool by creating and initializing an NSAutoreleasePool, running some code, and then draining the pool. So far so good; I'm using this functionality around most of my entry points into the ObjectiveC world. There's two issues I don't understand though. The first is that NSAutoreleasePool initialization seems to require an active autorelease pool, which seems like a chicken-and-egg problem. Running with OBJC_DEBUG_MISSING_POOLS=YES and breaking on objc_autoreleaseNoPool, I see: objc[30336]: MISSING POOLS: (0x1e2e89c40) Object 0x6000007e0050 of class __NSCFString autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug (lldb) bt objc_autoreleaseNoPool at /usr/lib/libobjc.A.dylib (unknown line) _ZN19AutoreleasePoolPage17autoreleaseNoPageEP11objc_object at /usr/lib/libobjc.A.dylib (unknown line) _ZN19AutoreleasePoolPage4pushEv at /usr/lib/libobjc.A.dylib (unknown line) _CFAutoreleasePoolPush at /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation (unknown line) -[NSAutoreleasePool init] at /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation (unknown line) macro expansion at /Users/tim/Julia/pkg/ObjectiveC/src/syntax.jl:163 [inlined] NSAutoreleasePool at /Users/tim/Julia/pkg/ObjectiveC/src/foundation.jl:427 The second, related problem is that some APIs that are called by Metal from a background thread I don't control: (lldb) bt * thread #11, queue = 'com.Metal.CompletionQueueDispatch', stop reason = breakpoint 1.1 * frame #0: 0x000000018c21b9e8 libobjc.A.dylib`objc_autoreleaseNoPool frame #1: 0x000000018c1eb99c libobjc.A.dylib`AutoreleasePoolPage::autoreleaseNoPage(objc_object*) + 252 frame #2: 0x000000018c21c9ec libobjc.A.dylib`AutoreleasePoolPage::push() + 76 frame #3: 0x00000001aaef9694 IOGPU`-[IOGPUMetalBuffer dealloc] + 104 frame #4: 0x00000001f83554e4 AGXMetalG15X_B0`-[AGXBuffer dealloc] + 44 frame #5: 0x00000001f837eb98 AGXMetalG15X_B0`-[AGXG15XFamilyBuffer dealloc] + 76 frame #6: 0x000000019687c1c4 Metal`MTLResourceListChunkFreeEntries(MTLResourceListChunk*) + 64 frame #7: 0x000000019674e2b0 Metal`-[MTLResourceList releaseAllObjectsAndReset] + 72 frame #8: 0x00000001aaefbd10 IOGPU`IOGPUMetalCommandBufferStorageReset + 36 frame #9: 0x00000001aaefbcac IOGPU`IOGPUMetalCommandBufferStorageDealloc + 76 frame #10: 0x00000001aaefa130 IOGPU`-[IOGPUMetalCommandBuffer didCompleteWithStartTime:endTime:error:] + 240 frame #11: 0x000000019674dce4 Metal`-[_MTLCommandQueue commandBufferDidComplete:startTime:completionTime:error:] + 108 frame #12: 0x00000001aaf03b54 IOGPU`IOGPUNotificationQueueDispatchAvailableCompletionNotifications + 128 frame #13: 0x00000001aaf03c60 IOGPU`__IOGPUNotificationQueueSetDispatchQueue_block_invoke + 64 frame #14: 0x000000018c4049d0 libdispatch.dylib`_dispatch_client_callout4 + 20 frame #15: 0x000000018c420c5c libdispatch.dylib`_dispatch_mach_msg_invoke + 468 frame #16: 0x000000018c40bd28 libdispatch.dylib`_dispatch_lane_serial_drain + 368 frame #17: 0x000000018c421998 libdispatch.dylib`_dispatch_mach_invoke + 444 frame #18: 0x000000018c40bd28 libdispatch.dylib`_dispatch_lane_serial_drain + 368 frame #19: 0x000000018c40ca08 libdispatch.dylib`_dispatch_lane_invoke + 432 frame #20: 0x000000018c40bd28 libdispatch.dylib`_dispatch_lane_serial_drain + 368 frame #21: 0x000000018c40c9d4 libdispatch.dylib`_dispatch_lane_invoke + 380 frame #22: 0x000000018c41761c libdispatch.dylib`_dispatch_root_queue_drain_deferred_wlh + 288 frame #23: 0x000000018c416e90 libdispatch.dylib`_dispatch_workloop_worker_thread + 404 frame #24: 0x000000018c5b2114 libsystem_pthread.dylib`_pthread_wqthread + 288 (lldb) c Process 26902 resuming objc[26902]: MISSING POOLS: (0x1e2e89c40) Object 0x14c8a2400 of class AGXG15SDevice autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug Again, I'm not sure how I'm supposed to run this under an autorelease pool.
3
0
552
Mar ’24
The replacement of NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)
I currently found out that the NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? NSMutableArray) is depreciated and is recommended by the compiler to use NSKeyedUnarchiver.unarchivedObject(ofClass: NSMutableArray.self, from: data) instead. However, the NSKeyedUnarchiver.unarchivedObject always return nil. Our original NSMutableArrary, named array, stores our objects, such as, public class TestInfo { public var name1 = "" public var name2 = "" .... } those objects were set by using: NSKeyedArchiver.archivedData(withRootObject: array, requiringSecureCoding: false) set(data, forKey: key) We had tried several different methods such as: NSKeyedUnarchiver.unarchivedObject(ofClass: NSMutableData.self, from: data) but all failed with return value nil. Is there better replacement of "unarchiveTopLevelObjectWithData" there to use? Thanks
2
0
251
Feb ’24
NSLock broken when using optimize speed in XCode Swift?
Dear Sirs, I've written a SwiftUI application in XCode where I'm using multiple threads which are synchronized by using NSLock and NSRecursiveLock. This works in Debug mode and in Release mode as long as I don't use the Swift Compiler - Code Generation -&gt; Optimization Level -O for "Optimize for Speed". This is unfortunately the default setting but it results in multiple threads accessing the same piece of code which is encapsulated inside a NSLock. Is this an intended behaviour? Thanks and best regards, Johannes
6
0
657
Mar ’24
ProcessInfo isLowPowerMode never changes during the same app session regarding the settings
I'm experiencing that issue but not on all devices, right now we are able to see a consistent behavior on iPhone 8 with iOS 16.7.5. The NSProcessInfoPowerStateDidChange is never called and the state is never updated during the same app session, it keeps returning the same value. Most weird the systemUptime changes, isLowPowerModeEnabled is the only state that never changes. Tried different approach even polling but the result is always the same. the problem doesn't seems to be in the code, even DataDog SDK (integrated in the same app), that asks the isLowPowerModeEnabled to understand if it could upload logs is affetcted by the same issue. protocol SystemPowerInfoProvider { var isLowPowerModeEnabled: AnyPublisher<Bool, Never> { get } } final class DefaultSystemBatteryOptimizationStateProvider: SystemPowerInfoProvider { var isLowPowerModeEnabled: AnyPublisher<Bool, Never> { _isLowPowerModeEnabled } private lazy var _isLowPowerModeEnabled: AnyPublisher<Bool, Never> = { return Just(ProcessInfo.processInfo.isLowPowerModeEnabled) .merge(with: NotificationCenter.default .publisher(for: Notification.Name.NSProcessInfoPowerStateDidChange) .map { notification -> Bool? in guard let processInfo = notification.object as? ProcessInfo else { return nil } return processInfo.isLowPowerModeEnabled } .compactMap { $0 } ) .eraseToAnyPublisher() }() }
1
0
446
Mar ’24
Does URL.query(percentEncoded:) calls URL.host(percentEncoded:) under the hood?
I see that there is a known issue about URL.host(percentEncoded:) to raise an EXC_BREAKPOINT crash on iOS 16. I used Url.query(percentEncoded:) and it triggered a crash on iOS 16 but the exception is shown at Url.host() instead of Url.query(). So, is there a chance that Url.query() calls Url.host() under the hood? I was able to resolve the crash by replacing Url.query(percentEncoded:) with the older API Url.query, but I don't understand that why would accessing the query would also access the host?
4
0
514
Mar ’24
smc keys for M3 pro chip, returning temperature values
Im honestly a bit lost and looking for general pointers. Here is the general flow of my project. I have an Xcode project where I want to return and convert the temperature values accessed from the apple smc and I found a GitHub repo with all the smc key sensors for the M3Pros/Max chips: https://github.com/exelban/stats/issues/1703 basically, I have all these keys stored in an array in obj-c like so: NSArray *smcKeys = @[ @"Tp01", @"Tp05", @"Tp09", @"Tp0D", @"Tp0b", @"Tp0f", @"Tp0j", @"Tp0n",@"Tp0h", @"Tp0L", @"Tp0S", @"Tp0V", @"Tp0z", @"Tp0v", @"Tp17", @"Tp1F", @"Tp1J", @"Tp1p", @"Tp1h", @"Tp1R", ]; I am passing all these keys by passing 'smcKeys' in a regular C code file I have here that is meant to open, close and read the data shown here: #include "smc.h" #include <mach/mach.h> #include <IOKit/IOKitLib.h> #include "smckeys.h" io_connect_t conn; kern_return_t openSMC(void) { kern_return_t result; kern_return_t service; io_iterator_t iterator; service = IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("AppleSMC"), &iterator); if(service == 0) { printf("error: could not match dictionary"); return 0; } result = IOServiceOpen(service, mach_task_self(), 0, &conn); IOObjectRelease(service); return 0; } kern_return_t closeSMC(void) { return IOServiceClose(conn); } kern_return_t readSMC(char *smcKeys, SMCVal_t *val) { kern_return_t result; uint32_t keyCode = *(uint32_t *)smcKeys; SMCVal_t inputStruct; SMCVal_t outputStruct; inputStruct.datasize = sizeof(SMCVal_t); inputStruct.datatype = 'I' << 24; //a left shift operation. turning the I into an int by shifting the ASCII value 24 bits to the left inputStruct.data[0] = keyCode; result = IOConnectCallStructMethod(conn, 5, &inputStruct, sizeof(SMCVal_t), &outputStruct, (size_t*)&inputStruct.datasize); if (result == kIOReturnSuccess) { if (val -> datasize > 0) { if (val -> datatype == ('f' << 24 | 'l' << 16 | 't' << 8 )) { //bit shifting to from 32bit operation associated with the ASCII charecters'f', 'l', and 't', sets datatype field. double temp = *(double *)val -> data; return temp; } } } return 0.0; } Which I am then then calling the functions from this file in a swift file and converting the values to Fahrenheit but no data is being printed in my console: import IOKit public class getTemperature { public struct SMCVal_t { var datasize: UInt32 var datatype: UInt32 var data: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) } @_silgen_name("openSMC") func openSMC() -> kern_return_t @_silgen_name("closeSMC") func closeSMC() -> kern_return_t @_silgen_name("readSMC") func readSMC(key: UnsafePointer<CChar>?,val: UnsafeMutablePointer<SMCVal_t>) -> kern_return_t func convertAndPrintTempValue(key:UnsafePointer<CChar>?,scale: Character, showTemp: Bool ) -> kern_return_t { let openSM = openSMC() guard openSM == 0 else { print("Failed to open SMC: \(openSM)") return kern_return_t() } let closeSM = closeSMC() guard closeSM == 0 else { print("could not close SMC: \(closeSM)") return IOServiceClose(conn) } func convertAndPrint(val: SMCVal_t) -> Double { if val.datatype == (UInt32("f".utf8.first!) << 24 | UInt32("l".utf8.first!) << 16 | UInt32("t".utf8.first!) << 8) { let extractedTemp = Double(val.data.0) return( extractedTemp * 9.0 / 5.0 + 32.0 ) } return 0.0 } let smcValue = SMCVal_t(datasize: 0, datatype: 0, data: (0,0,0,0,0,0,0,0)) let convertedVal = convertAndPrint(val: smcValue) print("Temperarure:\(convertedVal)F°") return kern_return_t() } } I know this is a lot but I am honestly looking for any tips to fill in any gaps in my knowledge for anyone who's built a similar application meant to extract any sort of data from Mac hardware.
1
0
522
Feb ’24
Did autorelease pools become no-ops? Look at this memory usage graph!
Have an app in the store - 10K users. Using the same algorithm for years to download objects, convert them to ManagedObjects, then save them in a context. Been using the exact same Objective-C code for over 5 years - no changes. We build the app with Xcode 15.1, release it a few weeks ago, then slowly start getting reports of the app won't boot. Run the app in 15.1, look at memory usage, and it's a flat line up. But the code is littered with autorelease statements. For this download, max memory was 2.3G! No wonder so many users crashing! [Worked two weekends straight to get this fixed, but why did it happen???] The last developer told me he added those to reduce memory pressure, and that they worked for him. (Unfortunately no old memory usage graphs). But look at the attached image - memory usage increments in a straight line - no saw tooth where memory would get released. Oh, and this is in one runloop on the main thread (don't blame me, I didn't write the original code!):
2
0
326
Feb ’24
Error Domain=NSCocoaErrorDomain Code=257
Hello, I have created a documentspicker to select a PDF file and then upload it to storage, but I am getting this error only on my device; it works correctly on the simulator. This is my code: @Binding var alertShow:Bool var detailpet:String = "" func makeCoordinator() -> Coordinator { return DocumentPicker.Coordinator(parent1: self) } func makeUIViewController(context: UIViewControllerRepresentableContext<DocumentPicker>) -> UIDocumentPickerViewController { let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.pdf]) picker.allowsMultipleSelection = false picker.delegate = context.coordinator return picker } func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: UIViewControllerRepresentableContext<DocumentPicker>) { } class Coordinator : NSObject, UIDocumentPickerDelegate { var parent:DocumentPicker init(parent1: DocumentPicker){ parent = parent1 } func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls:[URL]) { let bucket = Storage.storage().reference() let db = Firestore.firestore() let collection = "documents" guard let url = urls.first, url.startAccessingSecurityScopedResource() else { return } DispatchQueue.main.async { url.stopAccessingSecurityScopedResource() print("Documents Picker stop") } let referenceDocument = bucket.child("docu/\(url.deletingPathExtension().lastPathComponent)") let _ = referenceDocument.putFile(from:url, metadata: nil) { metadata , error in guard metadata != nil else{ print("Error \(String(describing: error?.localizedDescription))") return } referenceDocument.downloadURL { url, error in guard let url = url else { print("Message error \(String(describing: error?.localizedDescription))") return } let _ = try? db.collection(collection).addDocument(from:DocumentData(idpet:self.parent.detailpet, name: "\(url.deletingPathExtension().lastPathComponent).pdf", url: url.absoluteString)) } print("Succes") self.parent.alertShow.toggle() } } } } t seems to be a permissions issue, I believe. Do you know how I can fix this? It's my first application. Thank you.
1
0
294
Feb ’24
Swift app crash with mutateError on NSMutableString object
Here's my codes: extension NSMutableString { func clear() { replaceCharacters(in: NSRange(location: 0, length: length), with: String(data: Data.init(repeating: 0, count: length), encoding: .utf8)!) replaceCharacters(in: NSRange(location: 0, length: length), with: "") } } My app receive some random rare crash report on the line: replaceCharacters(in: NSRange(location: 0, length: length), with: String(data: Data.init(repeating: 0, count: length), encoding: .utf8)!) Crash logs: Last Exception Backtrace: 0 CoreFoundation 0x19f228870 __exceptionPreprocess + 164 (NSException.m:249) 1 libobjc.A.dylib 0x197543c00 objc_exception_throw + 60 (objc-exception.mm:356) 2 CoreFoundation 0x19f2f0d10 _CFThrowFormattedException + 108 (CFObject.m:2245) 3 CoreFoundation 0x19f26094c mutateError + 96 (CFObject.m:599) 4 CoreFoundation 0x19f185770 -[__NSCFString replaceCharactersInRange:withString:] + 72 (CFObject.m:608) 5 MyApp 0x10122c67c NSMutableString.clear() + 224 (NSMutableString.swift:22) 6 MyApp 0x1012974f4 UserData.loggedOut() + 56 (UserData.swift:58) 7 MyApp 0x100fac7dc AuthenticationManager.didLogout(isSessionExpired:preventAutoLoginByFaceID:) + 60 (AuthenticationManager.swift:200) The thing is I couldn't reproduce it and the crash is rare so I run out of idea, and would hope to receive some suggestions from the forum. Thank you.
1
0
204
Feb ’24
what does this mean?!? "Argument passed to call that takes no arguments"
this is where the problem is let randomXStart = arc4random(min: CGRectGetMinX(gameArea), max: CGRectGetMaxX(gameArea)) let randomXEnd = arc4random(min: CGRectGetMinX(gameArea), max: CGRectGetMaxX(gameArea)) for some reason it says to delete it but when i do, it doesnt work btw im just following a video so please dumb it down for me this is all the code for the section it's located in func spawnEnemy (){ let randomXStart = arc4random(min: CGRectGetMinX(gameArea), max: CGRectGetMaxX(gameArea)) let randomXEnd = arc4random(min: CGRectGetMinX(gameArea), max: CGRectGetMaxX(gameArea)) let startPoint = CGPoint(x: randomXStart, y: self.size.height * 1.2) let endPoint = CGPoint(x: randomXEnd, y: self.size.height * 0.2) let Dino = SKSpriteNode(imageNamed: "BlueDino") Dino.setScale(1) Dino.position = startPoint Dino.zPosition = 2 self.addChild(Dino) let moveDino = SKAction.moveTo(endPoint, duration: 1.5) let deleteDino = SKAction.removeFromParent() let dinoSequence = SKAction.sequence([moveDino, deleteDino]) Dino.run(dinoSequence) let dx = endPoint.x - startPoint.x let dy = endPoint.y - startPoint.y let amountToRotate = atan2(dy, dx) Dino.zRotation = amountToRotate
3
0
386
Feb ’24