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

NSURLSessionDataTask changes between iOS 16 to iOS 17?
I have an issue where performing a 'POST' request fails with a 400 when done on a device running iOS 16, but succeeds with a 200 on devices running iOS 17. I have not been able to find any explanations for this behavior. I've checked the request on both versions and it's identical in both versions of iOS, as far as I can tell. BodyStream : JSON object data Headers : Content-Type:application/json TimeoutInterval: 900
1
0
493
Apr ’24
OrderedDictionary encode issue
Hi all, Here I want to encode OrderedDictionary to JSON file, I use the JSONEncoder below: let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .withoutEscapingSlashes] and I declare variables qwe, asd and zxc: var qwe = OrderedDictionary<String, Int>() qwe["bbb"] = 12 qwe["ccc"] = 13 qwe["ddd"] = 14 qwe["bbc"] = 15 var asd = Dictionary<String, Int>() asd["bbb"] = 1 asd["ccc"] = 3 asd["ddd"] = 4 asd["bbc"] = 5 var zxc: KeyValuePairs<String, String> { return [ "zz": "zz", "aa": "aa", "bb": "bb", "cc": "cc", "bc": "bc", ] } After I do try encoder.encode(qwe).write(to: path ,options: .atomic) encoder.encode(asd).write(to: path ,options: .atomic) encoder.encode(zxc).write(to: path ,options: .atomic) the output JSON file format of OrderedDictionary isn't what I expected. The output JSON of OrderDictionary is like this: [ "bbb", 12, "ccc", 13, "ddd", 14, "bbc", 15 ] On the other hand, the output JSON of Dictionary and KeyValuePairs are normal, just with different order: Dictonary: { "ccc" : 3, "bbb" : 1, "bbc" : 5, "ddd" : 4 } KeyValuePairs: { "cc" : "cc", "aa" : "aa", "zz" : "zz", "bb" : "bb", "bc" : "bc" } I also Log these objects after I declare them, the Log show their structure are similar: qwe -> ["bbb": 12, "ccc": 13, "ddd": 14, "bbc": 15] asd -> ["ccc": 3, "bbb": 1, "bbc": 5, "ddd": 4] zxc -> ["zz": "zz", "aa": A"aa", "bb": "bb", "cc": "cc", "bc": "bc"] I thought the OrderedDictionary is similar to Dictionary, but does anyone know why the output of OrderedDictionary is not like this: {"bbb": 12, "ccc": 13, "ddd": 14, "bbc": 15} Or is there any other way I can customize the order of keys in my encoded JSON file? Thank you so much!
1
0
386
Apr ’24
Priority Ordering of delegates for serving a Class with multiple delegates
It appears that when a class like the following: " class RoomCaptureViewController: UIViewController, RoomCaptureViewDelegate,ARSCNViewDelegate, MTKViewDelegate, ARSessionDelegate, RoomCaptureSessionDelegate. " has multiple delegates, the ordering of the priority of each message is delivered to a delegate by a priority sensitive order based algorithm and that one message can be processed by only one delegate and not passed off to other delegates if they don't have the proper entry points. Specifically I noted that changing the order seems to result in a delegate not getting a message that it should be seeing. Is there a "handoff" call that can be made after a delegate has seen a message but needs to pass it off to another delegate for processing? This is a protocol typically utilized in Interrupt handlers for PCIe and other messaging protocols and I have not been able to find a similar capability In the voluminous documentation available for IOS and Mac systems. I would also like to know how a message is dispatched by a class to the particular delegate for which the message was intended. Is there a detailed document that explains how the messaging protocol works that is not so fragmented as to require having multiple monitors open in order to form a coherent picture of the messaging interface for Delegates belonging to a class?
3
0
622
Apr ’24
no data from userdefaults
i have a save function: func save(){ if let encoded = try? JSONEncoder().encode(routes) { UserDefaults.standard.set(encoded, forKey: saveKey) } } and an init function: init() { if let data = UserDefaults.standard.data(forKey: saveKey){ print(data.base64EncodedString) if let decoded = try? JSONDecoder().decode([RouteObject].self, from: data) { routes = decoded return } } routes = [] } onload this initiation there is no data. but 3382 bytes how get I the content form data? i don't know where the error is? debug is not possible I did get the info
5
0
965
Apr ’24
A user is unable to download content in app
I have an app with IAP which uses a URLSession object to download files from a server. The download part of the code is: let request = URLRequest(url: fromURL, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeoutInterval) let (data, response) = try await downloadSession.data(for: request) This code has been working without trouble for over a year with thousands of downloads. Now I have a user with a new iPhone (iOS 17.3.1) which refuses to download, failing at the above code (judging by the high level logs). My question is this: What sort of things should we be looking at in order to diagnose this issue? So far we have done the following: He has no general download issue (eg Safari works fine) His network access is 'normal' and the problem persists when the network is changed (4G, wifi etc) He runs a VPN (Nord) but the problem persists when this is off He has no 3rd party AV software His phone is not in lockdown mode Any pointers would be appreciated! NB I have no physical access to his device (yet!)
2
0
602
Apr ’24
URL.checkResourceIsReachable() throws error if file is on FTP server and name contains special characters
I have a file named ä.txt (with German umlaut) on my FTP server. I select it like this: let openPanel = NSOpenPanel() openPanel.runModal() let source = openPanel.urls[0] Running this code unexpectedly throws an error: do { print(try source.checkResourceIsReachable()) } catch { print(error) // Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory” } Manipulating the URL also seems to change the underlying characters: print(source) // file:///Volumes/abc.com/httpdocs/%C3%A4.txt print(URL(fileURLWithPath: source.path)) // file:///Volumes/abc.com/httpdocs/a%CC%88.txt Note that both variants of the URL above also throw the same error when running URL.checkResourceIsReachable(). If I download the file to my Mac, then both variants print file:///Users/me/Downloads/a%CC%88.txt and neither of them throws an error when running URL.checkResourceIsReachable(). What is the problem? How can I correctly access this file on the FTP server?
6
0
714
Apr ’24
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 -&gt; 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 -&gt; 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
536
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
331
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
603
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
577
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
820
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
527
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
524
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
967
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
337
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
978
Mar ’24