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

201 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

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
342
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
525
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
670
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
2
2
1.4k
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
724
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
380
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 -> 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
800
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
551
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
648
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
672
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
423
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
382
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
260
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
532
Feb ’24
NSTextField and NSAttributedString
I'm trying to put an attributed string in to an NSTextField the user creates in their document. I cannot use an NSTextView. The problem is once the textfield is created attributes cannot be edited. Also I work in Objective-c because reasons. So when the field is created this is the code used: [attribDict setObject:[self.editor.delegate foregroundColor] forKey:NSForegroundColorAttributeName]; [attribDict setObject:aFont forKey:NSFontAttributeName]; [attribDict setObject:[self.editor.delegate backgroundColor] forKey:NSBackgroundColorAttributeName]; [attribDict setObject:self.editor.delegate.strokeColor forKey:NSStrokeColorAttributeName]; [attribDict setObject:[NSNumber numberWithInt:-self.editor.delegate.strokeWidth] forKey:NSStrokeWidthAttributeName]; This part works if I set all the attributes before I create the textfield. But I need to be able to edit attributes on the string. For that I use this code: NSFont * aFont = [NSFont fontWithName:self.delegate.fontSelectorButton.title size:self.delegate.fontSize.intValue]; NSMutableDictionary * attribDict = [[NSMutableDictionary alloc]init]; [attribDict setObject:[self.delegate foregroundColor] forKey:NSForegroundColorAttributeName]; [attribDict setObject:aFont forKey:NSFontAttributeName]; [attribDict setObject:[self.delegate backgroundColor] forKey:NSBackgroundColorAttributeName]; [attribDict setObject:self.delegate.strokeColor forKey:NSStrokeColorAttributeName]; [attribDict setObject:[NSNumber numberWithInt:self.delegate.strokeWidth] forKey:NSStrokeWidthAttributeName]; [textShape updateTextAttributesFromDictionary:attribDict]; And finally this is called the change the string attributes: -(void)updateTextAttributesFromDictionary:(NSDictionary*)attribs { self.stringAttributes = attribs; NSMutableAttributedString * as = [[NSMutableAttributedString alloc]initWithAttributedString:self.myTextField.attributedStringValue]; [as beginEditing]; [as setAttributes:attribs range:NSMakeRange(0, as.length)]; [as endEditing]; self.myTextField.attributedStringValue = as; } I have tried just setting the new attributes and get nothing. The above code however gives me wildly unpredictable results. Sometimes the NSTextfield gets a background color that cannot be altered. Sometimes the text vanishes. Sometimes all attributes are lost, sometimes if I include a stroke color and width I get the stroke but no fill. That's the most common. Is there some fundimental NSTextField short coming I'm missing? Is there something I'm missing with NSAttributedString? Are NSAttributedStrings not compatible with NSTextField?
0
0
441
Feb ’24
Convert unix timestamp to Date failed.
I get and int unix timestamp from database and convert it to timeinterval as some instructions said. But the result date is not correct. the code is as follows: let dateValue = try join.get(examDate); print (dateValue) let timeInterval = TimeInterval(dateValue); print(timeInterval) let date = Date(timeIntervalSince1970: timeInterval) print(date) the result is as follows: 1709942400000 1709942400000.0 56155-12-02 00:00:00 +0000 by converting 1709942400000 with js Date, we got the value: &gt;new Date(1709942400000) 2024-03-09T00:00:00.000Z How can I properly convert unix timestamp to Date object? Thanks in advance.
1
0
877
Feb ’24
NSItemProvider throwing exception related to secure coding
Our app has a share extension. And we recently noticed something with iOS 17.3.1. From Safari, when we receive the plist and try to load it, we are seeing exceptions for classes not allowed to be unarchived. [itemProvider loadItemForTypeIdentifier:[UTTypePropertyList identifier] options:nil completionHandler:^(NSDictionary *jsDict, NSError *error) { } We see these exceptions: value for key 'NS.keys' was of unexpected class 'NSString' (0x1ee7d2970) [/System/Library/Frameworks/Foundation.framework]. Allowed classes are: {( "'NSDictionary' (0x1ee7cad38) [/System/Library/Frameworks/CoreFoundation.framework]" )} (null) Our preprocessing javascript file is basic, and only passes a title and URL as part of the payload. arguments.completionFunction({ "URL": document.URL "title": document.title, });
25
0
2.3k
Mar ’24
URLSession Task Types vs Session Types
I regularly see folks confused as to which URLSession task types are supported in which session types. Here’s a handy reference: Task Type Standard Background --------- -------- ---------- data, convenience yes no data, delegate yes yes [1] download, convenience yes no download, delegate yes yes upload, convenience yes no upload, delegate, data yes no upload, delegate, stream yes no upload, delegate, file yes yes stream yes no WebSocket yes no In this table: A background session is one created from a configuration that was created with the background(withIdentifier:) method. A standard session is one created from some other configuration, namely default or ephemeral. A convenience task is one created by a Swift async method or a method that takes a completion handler. A delegate task is one created otherwise; these signal their completion by calling the urlSession(_:task:didCompleteWithError:) delegate method. For an upload task, the data, stream, and file modifiers indicate how you specify the HTTP request body. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" [1] While it’s possible to run a data task in a background session, this only works if your app avoids suspension while the request is in flight. This is useful in very rare circumstances [2] that most developers never encounter. [2] The specific situation I’m aware of is when you don’t know whether a request’s response will be big (like a file to download) or small (like a status response). To handle this, you start a data task in the background session and, if the response indicates that it’s large, transform it to a download task in your urlSession(_:dataTask:didReceive:completionHandler:) method. (r. 123084713)
0
0
295
Feb ’24
Please help me understand “Finding the Dynamic Type in a Generic Context”
Please help me understand this section! I'm reading Finding the Dynamic Type in a Generic Context that has this snippet: func printGenericInfo<T>(_ value: T) { let t = type(of: value) print("'\(value)' of type '\(t)'") } protocol P {} extension String: P {} let stringAsP: P = "Hello!" printGenericInfo(stringAsP) // 'Hello!' of type 'P' ... that's followed up by this sentence: This unexpected result occurs because the call to type(of: value) inside printGenericInfo(_:) must return a metatype that is an instance of T.Type , but String.self (the expected dynamic type) is not an instance of P.Type (the concrete metatype of value). 1. How come String.self is not an instance of P when I can run this code? func f(_ t: P.Type) { print("...") } f(String.self) 2. Why does type(of:) return the concrete metatype outside but not inside generic functions? print("'\(stringAsP)' of type '\(type(of: stringAsP))'") // 'Hello!' of type 'String'
1
0
315
Feb ’24