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

294 Posts
Sort by:
Post marked as solved
2 Replies
110 Views
According to the WWDC 21 Session https://developer.apple.com/videos/play/wwdc2021/10109/ It shows how can we describe custom attributes in markdown as followings: This text contains ^[an attribute](rainbow: 'extreme'). This text contains ^[two attributes](rainbow: 'extreme', otherValue: 42). This text contains ^[an attribute with 2 properties](someStuff: {key: true, key2: false}). So, the first one, I can guess how to create, and last one could archive with describing Value type as a Struct. However, I don't know how to handle the second case. CodableAttributedStringKey and MarkdownDecodableAttributedStringKey allow us to override decoding function. but that decoding function's Decoder can only accept to access to the value which comes from first attribute. Like rainbow's container. So how can we take the value in otherValue as 42?
Posted
by
Post not yet marked as solved
1 Replies
184 Views
I'm working on an app where we want to upload data every 5 minutes or so to a cloud server even if the app is in the background. We're able to receive data from a BLE sensor in the background, but couldn't find anything on uploading the data consistently. We think it should be possible due to products like the Dexcom glucose monitoring system which uploads data from the background every 5 minutes. Any idea on how we'd go about doing this?
Posted
by
Post marked as solved
1 Replies
87 Views
We are now developing an online APP exam function,But students can cheat with keyboard custom phrases,How to turn off keyboard custom phrase hints?
Posted
by
Xjq
Post marked as solved
1 Replies
95 Views
https://imdb-api.com/en/API/BoxOffice/k_92uqzcls i cast data like this :  let output = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! Dictionary<String,Array<Dictionary<String, Any>>>//Array error: Could not cast value of type '__NSCFConstantString' (0x7fff869ca888) to 'NSArray' (0x7fff869ca8e8).
Posted
by
Post not yet marked as solved
1 Replies
168 Views
Apple's Certificate Transparency policy says that Signed Certificate Timestamps (SCTs) are accepted from TLS extension or OCSP Stapling in addition to the SCTs embedded in the certificate. If we're implementing our own Certificate Transparency enforcement in code written using URLSession, is there a way to obtain SCTs that were presented via TLS extension or OCSP Stapling? I'm able to get the SCTs from the certificate by calling SecCertificateCopyValues with "1.3.6.1.4.1.11129.2.4.2" inside the urlSession(_:didReceive:completionHandler:) delegate function. I see that there are functions for adding TLS/OCSP SCTs to the ServerTrust, but I don't see any functions for getting them out, and I don't know if URLSession would be including those SCTs in the ServerTrust automatically anyway. Is there any way to get these other SCTs using URLSession? Or would I have to drop down to Network Framework to do that? Thanks for any help.
Posted
by
Post marked as solved
3 Replies
164 Views
I've followed several tutorials and nothing works or is remotely simple. can anyone perhaps link a json tutorial that can load the following in a "SWIFT UI" format? { "id": 182, "name": "message 2048", "interactive": "https://wolvideos.firebaseapp.com/Test1.mp4", "thumbnail": "https://wolvideos.firebaseapp.com/back.jpg", "date": "April 1", "videolink": "https://player.vimeo.com/external/656370948.m3u8?s=e50ca2b440798886646ba88a07e9c46a90c9df11", "sharelink": "https://youtu.be/n7YjxFCyDNQ" }, { "id": 180, "name": "Title 4", "interactive": "https://wolvideos.firebaseapp.com/Test2.mp4", "thumbnail": "https://wolvideos.firebaseapp.com/back.jpg", "date": "April 2", "videolink": "https://player.vimeo.com/external/653500077.m3u8?s=96c687bef62bfd01ea195e4113e197ebd8d09143", "sharelink": "https://youtu.be/n7YjxFCyDNQ" }, { "id": 172, "name": "Titil 20203", "interactive": "https://wolvideos.firebaseapp.com/Test1.mp4", "thumbnail": "https://wolvideos.firebaseapp.com/back.jpg", "date": "April 1", "videolink": "https://player.vimeo.com/external/656370948.m3u8?s=e50ca2b440798886646ba88a07e9c46a90c9df11", "sharelink": "https://youtu.be/n7YjxFCyDNQ" }, { "id": 171, "name": "Title 20part2", "interactive": "https://wolvideos.firebaseapp.com/Test2.mp4", "thumbnail": "https://wolvideos.firebaseapp.com/back.jpg", "date": "April 2", "videolink": "https://player.vimeo.com/external/653500077.m3u8?s=96c687bef62bfd01ea195e4113e197ebd8d09143", "sharelink": "https://youtu.be/n7YjxFCyDNQ" }, { "id": 170, "name": "Title 2021", "interactive": "https://wolvideos.firebaseapp.com/Test1.mp4", "thumbnail": "https://wolvideos.firebaseapp.com/back.jpg", "date": "April 1", "videolink": "https://player.vimeo.com/external/656370948.m3u8?s=e50ca2b440798886646ba88a07e9c46a90c9df11", "sharelink": "https://youtu.be/n7YjxFCyDNQ" }, { "id": 169, "name": "Title 2020", "interactive": "https://wolvideos.firebaseapp.com/Test2.mp4", "thumbnail": "https://wolvideos.firebaseapp.com/back.jpg", "date": "April 2", "videolink": "https://player.vimeo.com/external/653500077.m3u8?s=96c687bef62bfd01ea195e4113e197ebd8d09143", "sharelink": "https://youtu.be/n7YjxFCyDNQ" } ] https://wolvideos.firebaseapp.com/Simple.json
Posted
by
Post not yet marked as solved
1 Replies
154 Views
recently my app published on app store facing some issue after i have implemented cloudflare and mtls to enhance security feature. Before that, when the API failed, i can receive http error code such as 403, 401 and etc. but after mtls is activated, all those failed http call is block by AppTransportSecurity layer and i can only receive 999 and error message as "URLSessionTask failed with error: The erver "***.***.com" requires a client certificate." i have read through Apple document, it says Apple introduce this security layer by default to ensure network security without known weakness https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW35 does anyone have come across similar issue like this before?
Posted
by
Post not yet marked as solved
1 Replies
122 Views
I'm getting errors when I use NSKeyedArchiver and NSKeyedUnarchiver that works with iOS 15.5 but not with iOS 12.4 nor iOS 12.5.5. I have tried combinations of using devices and simulators. The error message appears in the Xcode debug window when the catch scope handles an error that occurs when the following statement executes: try NSKeyedUnarchiver.unarchivedObject(ofClass: CNGroup.self, from: dataToUnarchive) Here is what prints in the Xcode debug window for Error.localizedDescription: The data couldn’t be read because it isn’t in the correct format. Here is what prints in the Xcode debug window when only the Error object is put in the print statement parentheses: Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x62, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4)" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x62, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4)} I found an answer to a similar question like this in Apple Developer Forums which had to do with NSCoder that indicated that the older iOS expects the Data object not to use secure coding, my code as this post concerns is not using secure coding. There are stackoverflow questions that deal with similar questions to mine, but they are very old and they deal with different facets of NSCoder. The following are the respective function definitions for archive(cnGroup:completionHandler:) and unarchive(dataOfCNGroup:completionHandler) that I use. Definition for unarchive(dataOfCNGroup:completionHandler) func archive(cnGroup: CNGroup, completionHandler: @escaping (Result<Data, Error>)->Void) { do { if #available(iOS 11.0, *) { let data: Data = try NSKeyedArchiver.archivedData(withRootObject: cnGroup, requiringSecureCoding: false) completionHandler(.success(data)) } else { let data: Data = NSKeyedArchiver.archivedData(withRootObject: cnGroup) completionHandler(.success(data)) } } catch { completionHandler(.failure(error)) } } // func archive(...) {...} Definition for archive(cnGroup:completionHandler:) func unarchive(dataOfCNGroup dataToUnarchive: Data, completionHandler: @escaping (Result<CNGroup, Error>)->Void) { print("func unarchive(dataOfCNGroup dataToUnarchive: Data, completionHandler: @escaping (Result<CNGroup, Error>)->Void)") do { if let unwrappedUnarchivedCNGroup: CNGroup = try NSKeyedUnarchiver.unarchivedObject(ofClass: CNGroup.self, from: dataToUnarchive) { completionHandler(.success(unwrappedUnarchivedCNGroup)) } else { let nsError = NSError(domain: "func unarchive(dataOfCNGroup dataToUnarchive: Data, completionHandler: @escaping (Result<CNGroup, Error>?)->Void)", code: #line, userInfo: nil) let error: Error = nsError completionHandler(.failure(error)) return } } catch { print("catch error in unarchive(dataOfCNGroup:_:) on line \(#line)") print("\(error.localizedDescription)") completionHandler(.failure(error)) } } // func unarchive(...) {...}
Posted
by
Post marked as solved
2 Replies
139 Views
TL;DR - the API cannot be changed, and the variable parameters are a vital part of my app. I've created a type that stores parameters for an API call. To make use of them with a successful request, I first need to format them into the URL. Say, my parameters are expressed as such: struct Parameters: Encodable { var name: String var taste: Taste var numberOfSpoons: Int? var topping: Taste? private enum CodingKeys: String, CodingKey { case name, taste, topping case numberOfSpoons = "spoons" } init(name: String, taste: Taste, numberOfSpoons: Int? = 1, topping: Taste? = nil){ self.name = name self.taste = taste self.numberOfSpoons = numberOfSpoons self.topping = topping } } Notice that my structure uses both Optionals (as the API does not need all the parameters from my app) and CodingKeys (as the names requested by the API look rather ugly in the code, but are necessary). Here's the Taste - not much going on except explicit Encodable conformance. enum Taste: String, Encodable { case choco, strawberry, vanilla } Now I want to call the API, so, according to the suggestion of John Sundell (I can't provide a link to the article due to Apple's censorship), I'm using URLComponents. For example: var components = URLComponents() components.scheme = "ftp" components.host = "icecream.ogs" components.path = "/spoons" If I were to add queryItems by hand, it would be fairly easy. components.queryItems = [ URLQueryItem(name: "name", value: iceCreamParameters.name), URLQueryItem(name: "numberOfSpoons", value: "\(iceCreamParameters.numberOfSpoons!)") ] How to dynamically create URLQueryItems from a non-CaseIterable type? The URLQueryItem needs both name and value parameters. I want the i-th name to be equal to I-thParameters.PropertyName, the same goes for values. As CaseIterable would not be feasible to implement* in the Parameters struct, I tried to fake it using the Encodable protocol - I thought about serializing the type to JSON (as the encoder gets rid of nil values, too) and then somehow get the keys from a deserialized Dictionary of AnyType (?), but there's got to be a better way. If this approach is not feasible, please provide your answers with helpful examples.
Posted
by
Post not yet marked as solved
1 Replies
116 Views
Xcode version: 13.2.1 (13C100) plateform: iOS Fatal Exception: NSInvalidArgumentException 0 CoreFoundation 0x99288 __exceptionPreprocess 1 libobjc.A.dylib 0x16744 objc_exception_throw 2 CoreFoundation 0x176fc4 +[NSObject(NSObject) _copyDescription] 3 CoreFoundation 0x2de98 forwarding 4 CoreFoundation 0x2cf70 _CF_forwarding_prep_0 5 QuartzCore 0xcb320 CA::Layer::run_animation_callbacks(void*) 6 libdispatch.dylib 0x3a30 _dispatch_client_callout 7 libdispatch.dylib 0x11f48 _dispatch_main_queue_drain 8 libdispatch.dylib 0x11b98 _dispatch_main_queue_callback_4CF 9 CoreFoundation 0x51800 CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE 10 CoreFoundation 0xb704 __CFRunLoopRun 11 CoreFoundation 0x1ebc8 CFRunLoopRunSpecific 12 GraphicsServices 0x1374 GSEventRunModal 13 UIKitCore 0x514648 -[UIApplication _run] 14 UIKitCore 0x295d90 UIApplicationMain 15 TCPApp 0xa44bb8 main + 39 (AppDelegate.swift:39) 16 ??? 0x104f49ce4 (Missing)
Posted
by
Post not yet marked as solved
0 Replies
122 Views
#define KdownloadsPath NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, YES).firstObject _downloadedPath = [KdownloadsPath stringByAppendingPathComponent:fileName]; _downloadingPath = [_downloadedPath stringByAppendingString:@".download"]; NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:         @"NSProgressFileOperationKindDownloading", @"NSProgressFileOperationKindKey",         [NSURL fileURLWithPath:_downloadingPath], @"NSProgressFileURLKey",         nil]; self.progress = [[NSProgress alloc] initWithParent:nil userInfo:info]; [self.progress setKind:@"NSProgressKindFile"]; [self.progress setPausable:NO]; [self.progress setCancellable:YES]; [self.progress setTotalUnitCount:_totalBytes]; [self.progress publish]; (updating the progress indicator happens elsewhere) I'm creating an NSProgress object to show a progress indicator underneat a file in my Downloads directory. The entitlements includes com.apple.security.files.downloads.read-write. The indicator does not show when NSProgressFileURLKey points to the sandboxed file path, e.g. /Users/mdbraber/Library/Containers/com.mdbraber.TestApp/Data/Downloads/Test.pptx.download. It does work when NSProgressFileURLKey points to the direct download location which the sandbox links to e.g. /Users/mdbraber/Downloads/Test.pptx.download Is this a bug or should I use something else for NSProgressFileURLKey to make this work?
Posted
by
Post not yet marked as solved
2 Replies
220 Views
As a follow-up to a Networking lab conversation I had on Tuesday I have the following question: Is there a way to use nscurl to connect to a server that requires client authentication by providing a client certificate? None of the documented options seem to allow that, but maybe there is an undocumented one...
Posted
by
Post not yet marked as solved
1 Replies
180 Views
I am using the URLSessionDownloadTask to download files and want the ability to pause the downloads. I want to use downloadTask.cancel(byProducingResumeData:) to achieve this and get the partially downloaded data. I want to get the actual file data from this plist but there is no straightforward way to do this. I see that we have a string with .tmp file extension in the plist (For e.g: CFNetworkDownload_yBD90c.tmp) and want to use that value to construct the path in tmp folder. I have seen in few discussions that the structure of this plist is not a constant and has gone though revisions in the past. Can I rely on this way to get the actual data from the plist? Alternatively, can anyone suggest other approach for this? (as I can not use the resume data directly since the request gets modified and this will be rejected by the server due to security reasons)
Post not yet marked as solved
0 Replies
257 Views
I've been trying to use the Xcode 14 beta and the -warn-concurrency flag to make some of our library code concurrency-safe, and I've hit just… too many problems to manage. A smattering of random data points: Foundation types that I think should be Sendable, are not: URL Notification ... UIKit constants that should not be @MainActor, are: UIApplication.willEnterForegroundNotification (it's just a string constant, and NotificationCenter itself is thread-safe) UIKit types and methods that I think should not be @MainActor, are: UIDevice, or at least I should be able to do UIDevice.current.systemVersion from any actor Dispatch is completely concurrency-unaware — I kinda expected it to be unavailable, but instead it's available but doesn't understand swift concurrency It'd at least be nice if DispatchQueue.main.[a]sync understood that its closure can be @MainActor (perhaps main could return a subclass of DispatchQueue with stronger guarantees?) SwiftUI Button etc. callbacks aren't marked @MainActor, even though (AFAIK) they are — certainly it's always been legal to update @State vars from them — so it's not legal to call UIKit from them (eg. to present a UIViewController in response to a button press) When can we expect Apple's SDKs to actually be usable with concurrency checking?
Posted
by
Post marked as solved
2 Replies
195 Views
Hi, I have a log to file function that as part of the logline inserts the current datetime as below: class func logToFile(message: String, logInfo: LogInfo = appLogInfo, type: OSLogType = .default) {           let formatter = DateFormatter()     formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"     formatter.timeZone = TimeZone(secondsFromGMT: TimeZone.current.secondsFromGMT())     formatter.locale = Locale(identifier: "en_US_POSIX")     let localDate = formatter.string(from: Date())           let logMessage = "\(localDate) [\(logInfo.category)] \(message)\n"           let documentDirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]           let filePath = "\(documentDirPath)/\(logFileName)"           if let fileHandle = FileHandle.init(forWritingAtPath: filePath), let data = logMessage.data(using: .utf8) {       fileHandle.seekToEndOfFile()       fileHandle.write(data)     }   } and it is always called from a serial queue: Log.serialQueue.async {       logToFile(message: message, logInfo: logInfo, type: type)     } Lately however, I am getting some crashes and I managed to catch one in the debugger. It happens when deallocating the local DateFormatter when exiting the logToFile function. Xcode stops at the end of the function: And the thread indicates that it is inside NSDateFormatter dealloc and clicking on the ici::Dataformat destructor, the assembly code shows this: And in the inspector, we can see that localDate is half-baked, it only contains the year and day: I have found some posts on DateFormatter not being thread safe but that was way in the past. In my case I only want to convert a Date() to String. Something is not working as expected and suggestions on how to improve it would be very welcome. Thanks in advance
Posted
by
Post not yet marked as solved
0 Replies
122 Views
General: 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 Low-Level Networking on watchOS DevForums post 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 on macOS: DevForums tag: Core WLAN Core WLAN framework documentation Secure networking: DevForums tags: Security Apple Platform Security support document Preventing Insecure Network Connections documentation — This is all about App Transport Security. 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 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 Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
Posted
by
Post not yet marked as solved
2 Replies
193 Views
I'm evaluating switching an application device from windows10 to macOS but one of the key features needed that I'm unsure of is kiosk mode in macOS. Does something like that exist? The application would need to be the only app running (in full screen) and nothing else should show up. Even keyboard shortcuts should be disabled. Is that configuration possible? Is it something to be done in the app program or does it need UWP kind of stuff? Thanks
Posted
by
CRX