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

337 Posts
Sort by:
Post not yet marked as solved
0 Replies
180 Views
First of all, I decided to make my project with only UIKit. So I deleted 'Main' storyboard, Info.plist->Storyboard name, and Main storyboard file base name->Main. And I edited SceneDelegate. So now I can display the single viewControllers, but when I try to set 'UITabBarController' to rootViewController, It cause this error(title). I tried to make UITabBarController in ViewController, UITabBarController in SceneDelegate and some more. // BackgroundViewController for the rootViewController import UIKit class BackgroundViewController: UIViewController { let backgroundTabBarController = UITabBarController() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white createTabBar() } } extension BackgroundViewController { private func createTabBar() { view.backgroundColor = .white view.addSubview(backgroundTabBarController.view) let firstViewController = BookSearchViewController() let secondViewController = MainViewController() let thirdViewController = UserStatusViewController() let lastViewController = OrderViewController() firstViewController.tabBarItem = UITabBarItem(title: "Search", image: UIImage(systemName: "magnifyingglass.circle.fill"), selectedImage: UIImage(systemName: "magnifyingglass.circle")) secondViewController.tabBarItem = UITabBarItem(title: "Main", image: UIImage(systemName: "house.fill"), selectedImage: UIImage(systemName: "house")) thirdViewController.tabBarItem = UITabBarItem(title: "My", image: UIImage(systemName: "person.fill"), selectedImage: UIImage(systemName: "person")) lastViewController.tabBarItem = UITabBarItem(title: "Order", image: UIImage(systemName: "menucard.fill"), selectedImage: UIImage(systemName: "menucard")) backgroundTabBarController.viewControllers = [firstViewController, secondViewController, thirdViewController, lastViewController] backgroundTabBarController.selectedViewController = secondViewController } } // SceneDelegate import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = (scene as? UIWindowScene) else { return } window = UIWindow(windowScene: windowScene) window?.rootViewController = BackgroundViewController() window?.makeKeyAndVisible() } } // Error code Thread 1: "Could not find a storyboard named 'Main' in bundle NSBundle </Users/[MyDesktopName]/Library/Developer/CoreSimulator/Devices/[ApplicationName]/data/Containers/Bundle/Application/[ApplicationName]/BTY.app> (loaded)" But anyone of this solve the problem. How can I make UITabBarController to rootViewController? Make UITabBarController in SceneDelegate Make new UIViewController that have UITabBarController and set to rootViewController Set ViewControllers with 'UINavigationController(rootViewController:)' Present UITabBarController from other viewController
Posted
by J_ROLF.
Last updated
.
Post not yet marked as solved
3 Replies
221 Views
We use UserDefaults in our app to identify if we already showed a particular UI to the user (so that it will not be shown to the user again). Our logic goes something like: if !UserDefaults.standard.alreadyShownToUser { showUI() UserDefaults.standard.alreadyShownToUser = true } But there are users who see this particular screen again when they open the app. The screen does not show up for a few days, and then suddenly, it shows up again. Our theory is that this might have something to do with iOS Prewarming. So we updated our code to add another check: if UIApplication.shared.isProtectedDataAvailable && !UserDefaults.standard.alreadyShownToUser However, it does NOT seem to work / mitigate the issue at all. We also added logs to check the value of UIApplication.shared.isProtectedDataAvailable and the value of the UserDefaults variable. We expected that if: UIApplication.shared.isProtectedDataAvailable is false, then the UserDefaults value should also be false. But in our logs, we can see that UIApplication.shared.isProtectedDataAvailable is false, but UserDefaults still returned true. Which led me to think that UserDefaults is not affected by Prewarming. Now, I'm back from the start. What's causing our UserDefaults to have different value? We also do not have anywhere else in the app that sets the value of UserDefaults.standard.alreadyShownToUser to false. The only time it should have that value is when the user installs the app for the first time. I appreciate any help that can lead me to fix this issue. Thank you!
Posted
by JennEve.
Last updated
.
Post marked as solved
5 Replies
422 Views
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
Posted Last updated
.
Post not yet marked as solved
2 Replies
216 Views
I use UserDefaults to store a variety of user data / preferences. Recently, I have started getting somewhat frequent complaints from users that their settings have been reset. There doesn't appear to be a rhyme or reason to the issue (some users have all of their data reset just once, while others are seeing that one of their settings resets very frequently). I haven't been able to pinpoint what the root cause is, but I figure that it must have something to do with UserDefaults (either all of it or only certain keys) somehow getting erased. As I figure out the root cause, I figure that a good solution in the meantime is to backup UserDefaults in some way (e.g. perhaps to iCloud?). Is there a standard / best-practice way of doing this?
Posted Last updated
.
Post not yet marked as solved
2 Replies
202 Views
I'm developing iOS framework with Objective C. I create a dispatch_queue_t by using dispatch_queue_create. And call CFRunLoopRun() for run the Runloop in the queue. But, It looks like the dispatch_queue_t has share the RunLoop. Some classes has add an invalid timer, and when I call the CFRunLoopRun(), It crashed on my side. Sample code: - (void)viewDidLoad { [super viewDidLoad]; self.queue1 = dispatch_queue_create("com.queue1", DISPATCH_QUEUE_CONCURRENT); self.queue2 = dispatch_queue_create("org.queue2", DISPATCH_QUEUE_CONCURRENT); } - (IBAction)btnButtonAction:(id)sender { dispatch_async(self.queue1, ^{ NSString *runloop = [NSString stringWithFormat:@"%@", CFRunLoopGetCurrent()]; runloop = [runloop substringWithRange:NSMakeRange(0, 22)]; NSLog(@"Queue1 %p run: %@", self.queue1, runloop); //NSTimer *timer = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:1 target:self selector:@selector(wrongSeletor:) userInfo:nil repeats:NO]; //[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; }); dispatch_async(self.queue2, ^{ NSString *runloop = [NSString stringWithFormat:@"%@", CFRunLoopGetCurrent()]; runloop = [runloop substringWithRange:NSMakeRange(0, 22)]; NSLog(@"Queue2 %p run: %@", self.queue2, runloop); CFRunLoopRun(); }); } Some time they take same RunLoop: https://i.stack.imgur.com/wGcv3.png ===== You can see the crash by uncomment the code of NSTimer. The NSTimer has been added in queue1, but it still running when call CFRunLoopRun() in queue2. I have read some description like: https://stackoverflow.com/questions/38000727/need-some-clarifications-about-dispatch-queue-thread-and-nsrunloop They told that: "system creates a run loop for the thread". But, in my check, they are sharing the RunLoop. This is sad for me, because I facing that crashes happen when calling CFRunLoopRun() on production. Can someone take a look at this.
Posted
by ninh.asus.
Last updated
.
Post not yet marked as solved
1 Replies
210 Views
Date/Time: 2024-04-11 09:58:14.2802 +0700 OS Version: macOS 14.4.1 (23E224) Report Version: 12 Anonymous UUID: BA4FE8B2-6345-D8DE-06FA-E30E32E93161 Time Awake Since Boot: 240 seconds System Integrity Protection: disabled Crashed Thread: 1 Exception Type: EXC_BAD_ACCESS (SIGABRT) Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000147d38000 Exception Codes: 0x0000000000000002, 0x0000000147d38000 Termination Reason: Namespace SIGNAL, Code 6 Abort trap: 6 Terminating Process: webstorm [1406] VM Region Info: 0x147d38000 is in 0x147d38000-0x147fa8000; bytes after start: 0 bytes before end: 2555903 REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL VM_ALLOCATE 138270000-147d38000 [250.8M] ---/rwx SM=ZER ---> VM_ALLOCATE 147d38000-147fa8000 [ 2496K] rwx/rwx SM=ZER VM_ALLOCATE 147fa8000-1482c8000 [ 3200K] ---/rwx SM=ZER Application Specific Information: abort() called Thread 0:: main Dispatch queue: com.apple.main-thread 0 libsystem_kernel.dylib 0x193c0e170 semaphore_wait_trap + 8 1 libdispatch.dylib 0x193a9e984 _dispatch_sema4_wait + 28 2 libdispatch.dylib 0x193a9f034 dispatch_semaphore_wait_slow + 132 3 webstorm 0x104acd8a4 std::sync::mpmc::context::Context::wait_until::hd085b5c0fb806785 + 108 4 webstorm 0x104ad0004 std::sync::mpmc::context::Context::with::$u7b$$u7b$closure$u7d$$u7d$::hc590ed29f2494e42 + 92 5 webstorm 0x104adaf60 xplat_launcher::main_lib::hd64975b96fde8651 + 8084 6 webstorm 0x104a719f0 std::sys_common::backtrace::__rust_begin_short_backtrace::h9840a7ca047c81ed + 12 7 webstorm 0x104a71c90 main + 660 8 dyld 0x1938c60e0 start + 2360 more detail in acttached file
Posted
by khoapv.
Last updated
.
Post not yet marked as solved
1 Replies
189 Views
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
Posted Last updated
.
Post not yet marked as solved
1 Replies
203 Views
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!
Posted Last updated
.
Post not yet marked as solved
3 Replies
236 Views
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?
Posted
by mfstanton.
Last updated
.
Post not yet marked as solved
2 Replies
256 Views
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!)
Posted
by Baylward.
Last updated
.
Post not yet marked as solved
1 Replies
201 Views
Hi, Is there any way to return cached URLSession response and then reload and return? I want show cached response while load last version of API call, and if reload works fine, show the latest version of response and in case os failure, show cached response (if exists) Thanks!
Posted Last updated
.
Post not yet marked as solved
1 Replies
239 Views
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 } }
Posted Last updated
.
Post not yet marked as solved
2 Replies
218 Views
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?
Posted Last updated
.
Post not yet marked as solved
1 Replies
163 Views
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)
Posted
by Tag_.
Last updated
.
Post not yet marked as solved
0 Replies
245 Views
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?
Posted
by Ash228.
Last updated
.
Post not yet marked as solved
10 Replies
4.7k Views
I've just updated to Xcode 15.3 and iOS 17.4 (simulator). Every time I launch the app, I see a CPU spike keeping the CPU at 100% for about 30 seconds on a background thread. After those 30 seconds, there's a 'Thread Performance Checker' error posted on the console. This does not happen when using Xcode 15.2 and running on iOS 17.2. or iOS 16.4. Thread Performance Checker: Thread running at User-initiated quality-of-service class waiting on a thread without a QoS class specified (base priority 33). Investigate ways to avoid priority inversions PID: 70633, TID: 2132693 Backtrace ================================================================= 3 CFNetwork 0x000000018454094c estimatedPropertyListSize + 28648 4 CFNetwork 0x00000001843d7fc0 cfnTranslateCFError + 1864 5 libdispatch.dylib 0x000000010557173c _dispatch_client_callout + 16 6 libdispatch.dylib 0x0000000105573210 _dispatch_once_callout + 84 7 CFNetwork 0x00000001843d7f8c cfnTranslateCFError + 1812 8 CFNetwork 0x0000000184540814 estimatedPropertyListSize + 28336 9 libdispatch.dylib 0x000000010557173c _dispatch_client_callout + 16 10 libdispatch.dylib 0x0000000105573210 _dispatch_once_callout + 84 11 CFNetwork 0x0000000184540728 estimatedPropertyListSize + 28100 12 CFNetwork 0x0000000184540794 estimatedPropertyListSize + 28208 13 libdispatch.dylib 0x000000010557173c _dispatch_client_callout + 16 14 libdispatch.dylib 0x0000000105573210 _dispatch_once_callout + 84 15 CFNetwork 0x0000000184540780 estimatedPropertyListSize + 28188 16 CFNetwork 0x00000001844e8664 _CFNetworkHTTPConnectionCacheSetLimit + 191584 17 CFNetwork 0x00000001844e78dc _CFNetworkHTTPConnectionCacheSetLimit + 188120 18 CFNetwork 0x000000018439ce5c _CFURLCachePersistMemoryToDiskNow + 25460 19 CFNetwork 0x0000000184483068 _CFStreamErrorFromCFError + 609680 20 CFNetwork 0x000000018445105c _CFStreamErrorFromCFError + 404868 21 CFNetwork 0x000000018443a040 _CFStreamErrorFromCFError + 310632 22 CFNetwork 0x000000018453be14 estimatedPropertyListSize + 9392 23 CFNetwork 0x000000018440fa5c _CFStreamErrorFromCFError + 137092 26 CFNetwork 0x000000018445b398 _CFStreamErrorFromCFError + 446656 27 CFNetwork 0x0000000184459db8 _CFStreamErrorFromCFError + 441056 28 CFNetwork 0x000000018445cf60 _CFStreamErrorFromCFError + 453768 29 CFNetwork 0x0000000184541838 estimatedPropertyListSize + 32468 30 libdispatch.dylib 0x000000010556fec4 _dispatch_call_block_and_release + 24 31 libdispatch.dylib 0x000000010557173c _dispatch_client_callout + 16 32 libdispatch.dylib 0x0000000105579a30 _dispatch_lane_serial_drain + 916 33 libdispatch.dylib 0x000000010557a774 _dispatch_lane_invoke + 420 34 libdispatch.dylib 0x000000010557b6e4 _dispatch_workloop_invoke + 864 35 libdispatch.dylib 0x00000001055871a8 _dispatch_root_queue_drain_deferred_wlh + 324 36 libdispatch.dylib 0x0000000105586604 _dispatch_workloop_worker_thread + 488 37 libsystem_pthread.dylib 0x0000000106b87924 _pthread_wqthread + 284 38 libsystem_pthread.dylib 0x0000000106b866e4 start_wqthread + 8
Posted
by xmollv.
Last updated
.