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

Habits Guide Project: nw_socket_handle_socket_event [C1.1.1:2] Socket SO_ERROR [61: Connection refused]
I keep getting the nw_socket_handle_socket_event [C1.1.1:2] Socket SO_ERROR [61: Connection refused] when I am trying to enter the HabitDetailView and UserDetailView. The server gives the information for the Habit/User Collection View (/habits and /users), but it does not give any of the images, UserStats or Habit Stats. I've posted below how the APIRequest and APIService code looks like. It just has me stumped that it gives some of the info, but blocks other parts. API Request import UIKit protocol APIRequest { associatedtype Response var path: String { get } var queryItems: [URLQueryItem]? { get } var request: URLRequest { get } var postData: Data? { get } } extension APIRequest { var host: String { "localhost" } var port: Int { 8080 } } extension APIRequest { var queryItems: [URLQueryItem]? { nil } var postData: Data? { nil } } extension APIRequest { var request: URLRequest { var components = URLComponents() components.scheme = "http" components.host = host components.port = port components.path = path components.queryItems = queryItems var request = URLRequest(url: components.url!) if let data = postData { request.httpBody = data request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" } return request } } API Service import UIKit struct HabitRequest: APIRequest { typealias Response = [String: Habit] var habitName: String var path: String { "/habits" } } struct UserRequest: APIRequest { typealias Response = [String: User] var path: String { "/users"} } struct HabitStatisticsRequest: APIRequest { typealias Response = [HabitStatistics] var habitNames: [String]? var path: String { "/habitStats"} var queryItems: [URLQueryItem]? { if let habitNames = habitNames { return [URLQueryItem(name: "names", value: habitNames.joined(separator: ","))] } else { return nil } } } struct UserStatisticsRequest: APIRequest { typealias Response = [UserStatistics] var userIDs: [String]? var path: String { "/userStats"} var queryItems: [URLQueryItem]? { if let userIDs = userIDs { return [URLQueryItem(name: "ids", value: userIDs.joined(separator: ","))] } else { return nil } } } struct HabitLeadStatisticsRequest: APIRequest { typealias Response = UserStatistics var userID: String var path: String { "/userLeadingStats" + userID} } struct ImageRequest: APIRequest { typealias Response = UIImage var imageID: String var path: String { "/images/" + imageID } } enum APIRequestError: Error { case itemsNotFound case requestFailed(HTTPURLResponse) } extension APIRequest where Response: Decodable { func send() async throws -> Response { let (data, response) = try await URLSession.shared.data(for: request) guard let httpResponse = response as? HTTPURLResponse else { throw APIRequestError.requestFailed(HTTPURLResponse()) } guard httpResponse.statusCode == 200 else { throw APIRequestError.itemsNotFound } let decoder = JSONDecoder() let decoded = try decoder.decode(Response.self, from: data) return decoded } } enum ImageRequestError: Error { case couldNotIntializeFromData case imageDataMissing } extension APIRequest where Response == UIImage { func send() async throws -> UIImage { let (data, response) = try await URLSession.shared.data(for: request) guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { throw ImageRequestError.imageDataMissing } guard let image = UIImage(data: data) else { throw ImageRequestError.couldNotIntializeFromData } return image } }
1
0
418
Apr ’24
A few questions about CodingKeys.
struct Meta: Codable { let isEnd: Bool enum CodingKeys: String, CodingKey { case isEnd = "is_end" } } let jsonStr = """ { "is_end" : true } """ let jsonData = jsonStr.data(using: .utf8)! do { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let result = try decoder.decode(Meta.self, from: jsonData) print(result) } catch { print(error) } Code written in the above manner will result in the corresponding error. keyNotFound(CodingKeys(stringValue: "is_end", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"is_end\", intValue: nil) (\"is_end\").", underlyingError: nil)) I think there is nothing wrong with the code. But why is the error occurring? And, Can't the enum be named something other than CodingKeys? like this, struct Meta: Codable { let isEnd: Bool enum CodingKeyss: String, CodingKey { case isEnd = "is_end" } } And these codes return normal results. What's the reason Meta(isEnd: true)
1
0
242
Apr ’24
Questions about isExcludedFromBackup option and device migration
Questions about isExcludedFromBackup option and device migration I posted a similar question a year ago, but I still haven't found a solution that I like, so I'm leaving this question. If anyone knows how, please let me know. In our app, we set the isExcludedFromBackup option to true so that files currently in the Documents path are not backed up to iCloud. In the current situation, I am just curious as to whether the files of our app can be backed up in the two situations below. (with isExcludedFromBackup option set to true ) Migrate iPhone to new iPhone Backup and restore the entire device to iTunes If you set the isExcludedFromBackup option to true in the file, iCloud backup will not be possible, and the app's internal files will not be copied even in the two situations mentioned above. Is there an option or method in the app's internal code to prevent automatic backup only to iCloud and allow files to be copied or synchronized in the above two situations?
2
0
392
Apr ’24
UIFileSharingEnabled isnt working on iOS 15.0
Hi, so following other tutorials on sharing app files to user I added and enabled LSSupportsOpeningDocumentsInPlace and UIFileSharingEnabled in info.plist. On app launch I create a sample file in the Documents Directory so that it shows up on the "On my iPhone" storage. I check this with the simulators for iOS17, iOS16 and it works fine, but for iOS15 it does not display the folder for my app. Does anyone have an idea on how to fix this?
0
0
399
Apr ’24
Multipeer Connectivity Framework Capabilities and Permission Requirements
Hello, In this inquiry(https://developer.apple.com/forums/thread/747860), I came across this conclusion. “Apple disabled TCP/IP networking over Bluetooth completely. Apple’s peer-to-peer networking APIs now run exclusively over Wi-Fi." I have three questions I would like to ask. The Multipeer Connectivity Framework supports Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks. Since the framework abstracts away the underlying protocols, we cannot specify which protocol to choose. Can this framework still establish a pure Bluetooth connection now? (Not just using Bluetooth for the discovery phase). Given that the framework supports Bluetooth protocols, why does it not require Bluetooth permissions but only local network permissions? Does the Bluetooth protocol supported by the framework have the capability to discover traditional Bluetooth devices and services that the Core Bluetooth framework can discover?
1
0
540
Apr ’24
Running .app bundled application in non GUI environment causing app to fail at runtime
I am having a bundled application(.app file) and I am wanting to run this application via ssh session which does not have GUI access. Launching this application in a desktop GUI session, runs the application perfectly. However, on running it on the same machine via ssh session produces an error. Note: My application does not bring up any GUI window(it' just produces some logs on the terminal), so running it in a non-GUI environment should have worked. I get the below error when trying to launch the unix exe in the .app bundle( ./Myapp.app/Contents/MacOS/Myapp ) on the terminal. I have observed that applicationDidFinishLaunching(_:) gets called and then the below error occurs. +[NSXPCSharedListener endpointForReply:withListenerName:replyErrorCode:]: an error occurred while attempting to obtain endpoint for listener 'ClientCallsAuxiliary': Connection interrupted I tried running other bundled applications via ssh, but all seems to produce the same error. Can someone confirm Is running bundled application in a non GUI session not allowed by Apple. If its allowed, how can I solve this? Even running the .app file using the open command fails to launch the application, although it produces a different error which is consistent across different applications.
1
0
422
Apr ’24
AVAssetDurationDidChange - notification not receiving in iOS 17
We utilized AVFragmentedAssetMinder to refresh the player data. While notifications for AVAssetDurationDidChange were consistently received whenever the player duration changed. However, following the release of iOS 17, notifications for AVAssetDurationDidChange ceased to be received. Could you please advise anyone why this notification is not being triggered? what we have to change NotificationCenter.default.addObserver(self, selector: #selector(self.onVideoUpdate), name: .AVAssetDurationDidChange, object: nil) #AVPLAyer, #AVMUtableMovie
0
0
397
Mar ’24
crash:__CFRunLoopServiceMachPort.cold.1 :56
After my project was packaged with Xcode15, the following crash occurred, which had not occurred before. After checking for a long time, the cause was not found, because similar problems did not occur when Xcode14 was used to package, so I think it is the problem caused by Xcode15 packaging Incident Identifier: 3DFEAAAC-DCEE-4C6F-B51D-29BE9448A9C0 CrashReporter Key: KSCrash2 Hardware Model: iPhone15,3 Process: KPlayi4Phone [11803] Path: /private/var/containers/Bundle/Application/FD3F5994-3F75-4477-B629-2343870A4995/KPlayi4Phone.app/KPlayi4Phone Identifier: com.KPlay.KPlay Version: 2035752548 (11.0.73) Code Type: ARM-64 Parent Process: ? [1] Date/Time: 2024-03-28 15:02:18 +0800 Launch Time: 2024-03-28 15:02:10 +0800 OS Version: iOS 16.2 (20C65) Report Version: 104 Exception Type: EXC_BREAKPOINT Exception Codes: KERN_INVALID_ADDRESS at 0x00000001d256402c Exception Subtype: SIGTRAP Triggered by Thread: 0 Thread 0 Crashed: 0 CoreFoundation 0x00000001d256402c __CFRunLoopServiceMachPort.cold.1 :56 (in CoreFoundation) 1 CoreFoundation 0x00000001d242ebd4 __CFBasicHashIncSlotCount :0 (in CoreFoundation) 2 CoreFoundation 0x00000001d242fd18 __CFRunLoopRun :1232 (in CoreFoundation) 3 CoreFoundation 0x00000001d2434ec0 _CFRunLoopRunSpecific :612 (in CoreFoundation) 4 GraphicsServices 0x000000020c48b368 _GSEventRunModal :164 (in GraphicsServices) 5 UIKitCore 0x00000001d492a86c -[UIApplication _run] :888 (in UIKitCore) 6 UIKitCore 0x00000001d492a4d0 _UIApplicationMain :340 (in UIKitCore) 7 KPlayi4Phone 0x0000000100f5608c main main.m:16 (in KPlayi4Phone) 8 ??? 0x00000001f0c56960 0x0000000000000000 + 8334436704 9 ??? 0x0000000000000000 0x0000000000000000 + 0 mycrash.crash
1
0
575
Apr ’24
What is the appropriate required reason level when using UserDefaults?
I saved the device token in UserDefaults. The information is passed on to the backend server of my app when needed. CA92.1: Declare this reason to access user defaults to read and write information that is only accessible to the app itself. I was thinking about using CA92.1, but that seems to mean reading and writing entirely within the app. 1C8F.1: Declare this reason to access user defaults to read and write information that is only accessible to the apps, app extensions, and App Clips that are members of the same App Group as the app itself. Can I see my app's backend server as belonging to "the apps, app extensions, and App Clips that are members of the same App Group"? Would it be okay to apply 1C8F.1?
1
0
272
Apr ’24
Xcode 15 iOS 12 app crash
We have a app , a few days before, we have start to build and archive to Appstore with the new Xcode 15.1, before update develop tools ,Xcode version is 14.2. Before update to new Xcode 15.1, the app works fine in iOS12 After our app reviewed by apple ,and release to the customer, we found crash in Xcode Organizer / Reports/Crashes module, and the system almost in iOS 12 Below is the photo And cann't found crash stack in other crash analysis tool such as Bugly。 Finally ,i found a device iPad mini, and can debug. Below is the XCode debug console. dyld: Symbol not found: OBJC_CLASS$_NSURLSessionTaskMetrics Referenced from: /private/var/containers/Bundle/Application/AA0D6934-6D78-4E2A-A822-F48FB29DC599/MosProject_Uat.app/Frameworks/Alamofire.framework/Alamofire Expected in: /System/Library/Frameworks/Foundation.framework/Foundation in /private/var/containers/Bundle/Application/AA0D6934-6D78-4E2A-A822-F48FB29DC599/productname_Uat.app/Frameworks/Alamofire.framework/Alamofire Message from debugger: killed And the crash log is same as we can found in Xcode crash log . It seams there is a bug in system Foundation.framework? Why cann't found the NSURLSessionTaskMetrics in system Foundation.framework? I have tried to relink the Foundation.framework, but cann't work. Anyone have same issue? Have any other ideas ? Thanks.
1
0
717
Mar ’24
NSURLSession times out after about 100 URLTasks
So I'm getting some weird behavior when using an NSURLSession. Our app uses two separate sessions. And we aren't doing anything special when making them. This is it: let configuration = URLSessionConfiguration.default configuration.waitsForConnectivity = false configuration.timeoutIntervalForResource = 30 self.init(configuration: configuration) All we do is create data tasks using session.dataTask(with: request) After creating about 100+ data tasks and having them complete successfully with no problems, the session will hang for the full 30 seconds and return a -1001 "The request timed out." error. The next few tasks on this session will fail, and then all of a sudden the NSURLSession will start working again. Now the weird part is... since I have two NSURLSessions, only the one that has hit 100+ tasks times out. The other NSURLSession can still contact the same server URL and run tasks just fine. I did put this through the Network Instrument and one thing I did see is that up until the timeout happens the NSURLSession will use a single connection as expected. But after the 30s timeout and the recovery it looks like the NSURLSession decides behind the scenes to make a brand new connection and that's where the "recovery" comes from. Out server team swears this isn't them as other non-iOS clients hitting the same endpoint don't have this error. Any help? (Side note: I can fix this in my app by just making a new NSURLSession every 100 tasks, but that doesn't really help me understand what could be going wrong in the first place).
2
0
463
Mar ’24
The right way to use start/stop AccessingSecurityScopedResource in swift-cpp interop
Hi, so I have this case where I would like the user to pick a folder where they want to create a file/folder using UIDocumentPicker/Browser and I make the file using open() in cpp and use its fd to read/write to the file. Now, the first thing is I have to call startAccessingSecurityScopedResource() on the directory url, then I make the file, get its fd(file descriptor) and I leave this makefile() function. Every startAccessingSecurityScopedResource() needs to be matched with a stopstartAccessingSecurityScopedResource(). So my question is do I 'have' to call stopAccessingSecurityScopedResource() 'just before' calling close() on the fd. Or is it fine to call it after I have made the fd i.e., at the end of the makefile() function? In the tests I did it seems that once the fd is opened, even if stopAccessingSecurityScopedResource() is called on it(the directory), I can continue to read/write from the fd until I close() the fd?
1
0
433
Mar ’24
Object 0x10bee2ff0 of class _DictionaryStorage deallocated with non-zero retain count 2
HI! Trying to figure out a particularly odd crash report (via crashlytics). Crashed: com.apple.main-thread 0 libsystem_kernel.dylib 0x7558 __pthread_kill + 8 1 libsystem_pthread.dylib 0x7118 pthread_kill + 268 2 libsystem_c.dylib 0x1d178 abort + 180 3 libswiftCore.dylib 0x3b93a8 swift::fatalError(unsigned int, char const*, ...) + 134 4 libswiftCore.dylib 0x3b93c8 swift::warningv(unsigned int, char const*, char*) + 30 5 libswiftCore.dylib 0x3bdfd8 swift_deallocPartialClassInstance + 190 6 libswiftCore.dylib 0x3bde28 _swift_release_dealloc + 56 7 libswiftCore.dylib 0x3bec4c bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1> >::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) + 132 8 PSStore 0xab8de0 ThankYouViewController.viewCleanup() + 32 (TwoPhaseCommitHelper.swift:32) Complete stackTrace here com.predictspring.pos_issue_63a57f567d9db225552c2cd24d915564_crash_session_7dfdc13304324dd39f1e60b48d20a6af_DNE_0_v2_stacktrace.txt The stack trace line that refers to our code points to a specific implementation of a ThreadedDictionary where we are removing all the objects inside the internal storage: We have not been able to reproduce this crash, however we are seeing multiple instances in our crash reports for it (All instances happening in iPadOS + 16.4.1 devices). Is there anything relevant to take a look in the first 7 frames of the crash report to understand what could be the issue? While researching on this, we identified a post with a very similar stacktrace entries: https://developer.apple.com/forums/thread/729196?login=true&page=1#752337022 We are not using GC or Unity, however the first entries in the stack trace look very similar. Rgds!
6
0
683
Mar ’24
FileDocument - open another file in the same directory as selected file
I'm working on a macOS app where my file format can include other files (think #include in C/C++). When opening a file with SwiftUI's document-based APIs (i.e., FileDocument), is there a way to get access to those other files? Alternatively, is there a way I could "open" the file's directory, similar to how Xcode opens the directory that a .xcodeproj is located? I don't mind falling back to older Cocoa APIs if this is too obscure for the shiny new stuff :)
3
0
550
2w
Process() object and async operation
I am maintaining a macOS app, a GUI on top of a command line tool. A Process() object is used to kick off the command line tool with arguments. And completion handlers are triggered for post actions when command line tool is completed. My question is: I want to refactor the process to use async and await, and not use completion handlers. func execute(command: String, arguments:[String]) -&gt; async { let task = Process() task.launchPath = command task.arguments = arguments ... do { try task.run() } catch let e { let error = e propogateerror(error: error) } ... } ... and like this in calling the process await execute(..) Combine is used to monitor the ProcessTermination: NotificationCenter.default.publisher( for: Process.didTerminateNotification) .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) .sink { _ in ..... // Release Combine subscribers self.subscriptons.removeAll() }.store(in: &amp;subscriptons) Using Combine works fine by using completion handlers, but not by refactor to async. What is the best way to refactor the function? I know there is a task.waitUntilExit(), but is this 100% bulletproof? Will it always wait until external task is completed?
2
0
519
Mar ’24
KeyedDecodingContainerProtocol - Why so many requirements?
The interface for the KeyedDecodingContainer protocol declares a bunch of requirements like such: func decode(_ type: Bool.Type, forKey key: Self.Key) throws -> Bool func decode(_ type: String.Type, forKey key: Self.Key) throws -> String func decode(_ type: Double.Type, forKey key: Self.Key) throws -> Double // etc. As well as a generic one: func decode<T>(_ type: T.Type, forKey key: Self.Key) throws -> T where T : Decodable Is that done for performance reasons? I have implemented a return-type-aware generic extension on KeyedDecodingContainer which always defers to the aforementioned generic implementation: func decode<Value: Decodable>( type: Value.Type = Value.self, _ key: Key ) throws -> Value { try decode(type, forKey: key) } Which allows me to decode anything in the following way: self.myValue = container.decode(.myValue) // instead of self.myValue = container.decode(String.self, forKey: .myValue) Now, this works fine and all, but upon submitting this extension for code review, one of my colleague raised concerns for defaulting to calling only the generic implementation rather than the statically-typed one (where applicable). So, my question is, are these concerns valid?
1
0
245
Mar ’24
NSMutableDictionary removeAllObjects does not free up used memory!
I have a custom Objective-C ObjectCache class that utilized NSMutableDictionary to store named objects (specifically large NSImage objects). The class has a maxItems property and clear method, which worked fine. - (void)clear { @synchronized(_cache) { [_cache removeAllObjects]; } } But yesterday I received a customer feedback complaining one of my app consumes up to 24GB memory. I verified that on my M1 Mac mini, and it's true. Even after calling clear method, memory usage shown in both Xcode debugger panel and Activity Monitor remains the same. It did work before. Once I close a picture gallery window by calling clear method, memory usage dropped immediately as shown in Activity Monitor. I suspect that this is a bug in ARM architecture. Does anyone else have same problem?
1
0
517
Mar ’24
Addressing App Crashes Due to Locked Files in Shared Containers on Background Transition
Hi everyone, I'm facing a critical issue with my app crashing when it goes into the background, and I'm hoping to find some advice or solutions from this knowledgeable community. My app utilizes a shared directory between itself and a FileProvider, alongside tdlib, which includes SQLite. The logic to work with tdlib is housed within a shared framework, which necessitates access to certain files by both the App and FileProvider. However, when I minimize the app, it crashes and logs the following error: [app<com.sedoyjan.keepgram(74B4C997-E6C2-4B65-8A31-CA1809248B01)>:3941] Terminating with context: <RBSTerminateContext| domain:15 code:0xDEAD10CC explanation:[app<com.sedoyjan.keepgram(74B4C997-E6C2-4B65-8A31-CA1809248B01)>:3941] was suspended with locked system files: /var/mobile/Containers/Shared/AppGroup/1F13B8D2-EC11-465C-85DE-2ED8797C5DF0/td/db.sqlite /var/mobile/Containers/Shared/AppGroup/1F13B8D2-EC11-465C-85DE-2ED8797C5DF0/td/td.binlog not in allowed directories: /var/mobile/Containers/Data/Application/8C035881-2676-4B92-A9AB-51A664D541C8 /var/mobile/Containers/Data/Application/8C035881-2676-4B92-A9AB-51A664D541C8/tmp reportType:CrashLog maxTerminationResistance:Absolute> This error suggests that the app is terminated due to having locked files within the shared container, which aren't allowed when the app is suspended. My question to the community is: Is there a way to keep the app running in the background without running into this issue with locked files in the shared container? Are there specific practices or architectural changes I should consider to prevent these crashes? Any advice, insights, or suggestions would be greatly appreciated as I navigate this challenge. Thank you in advance for your help!
1
0
349
Mar ’24