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

332 Posts
Sort by:
Post not yet marked as solved
0 Replies
4 Views
extension UIView { func takeSnapshot(rect : CGRect? = CGRect.zero) -> UIImage? { let renderer = UIGraphicsImageRenderer(size: frame.size) var image = renderer.image { _ in drawHierarchy(in: bounds, afterScreenUpdates: true) } if let imageRect = rect, imageRect != CGRect.zero { let screenshotFrame = CGRect(x: imageRect.origin.x * UIScreen.main.scale, y: imageRect.origin.y * UIScreen.main.scale, width: imageRect.size.width * UIScreen.main.scale, height: imageRect.size.height * UIScreen.main.scale) let imageRef = image.cgImage!.cropping(to: screenshotFrame) image = UIImage.init(cgImage: imageRef!, scale: image.scale, orientation: image.imageOrientation) } UIGraphicsEndImageContext() return image } } which was working fine until I updated to macOS 14.4.1 from 14.2.1 and to Xcode 15.3 from 15.0. issue From my Mac Catalyst app, if I try to take screenshot of imageView, the screenshot is brighter. If I try this method it seems working: func takeSnapshotWithoutScale() -> UIImage? { UIGraphicsBeginImageContextWithOptions(self.frame.size, false, 0) if let currentContext = UIGraphicsGetCurrentContext() { self.layer.render(in: currentContext) } let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage }
Posted Last updated
.
Post not yet marked as solved
1 Replies
14 Views
Xcode Version 15.0.1 (15A507) Crash log Hardware Model: iPhone14,7 Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] OS Version: iPhone OS 16.6 (20G75) Release Type: User Baseband Version: 1.80.02 Report Version: 104 Exception Type: EXC_CRASH (SIGABRT) Triggered by Thread: 26 Application Specific Information: abort() called Last Exception Backtrace: 0 CoreFoundation 0x1b3c54cb4 __exceptionPreprocess + 164 1 libobjc.A.dylib 0x1accf03d0 objc_exception_throw + 60 2 Foundation 0x1adf6950c -[NSData(NSData) _base64EncodingAsString:withOptions:] + 1072 3 Foundation 0x1ae2cf8bc Data.base64EncodedString(options:) + 640 ... 6 libdispatch.dylib 0x1bb11a320 _dispatch_call_block_and_release + 32 7 libdispatch.dylib 0x1bb11beac _dispatch_client_callout + 20 8 libdispatch.dylib 0x1bb11ef8c _dispatch_queue_override_invoke + 788 9 libdispatch.dylib 0x1bb12d944 _dispatch_root_queue_drain + 396 10 libdispatch.dylib 0x1bb12e158 _dispatch_worker_thread2 + 164 11 libsystem_pthread.dylib 0x213a85da0 _pthread_wqthread + 228 Thread 26 name: Dispatch queue: com.apple.root.default-qos Thread 26 Crashed: 0 libsystem_kernel.dylib 0x1f2c11578 __pthread_kill + 8 1 libsystem_pthread.dylib 0x213a8c118 pthread_kill + 268 2 libsystem_c.dylib 0x1bb17c178 abort + 180 3 libc++abi.dylib 0x2139cabf8 abort_message + 132 4 libc++abi.dylib 0x2139ba444 demangling_terminate_handler() + 348 5 libobjc.A.dylib 0x1accf5ea4 _objc_terminate() + 144 6 libc++abi.dylib 0x2139c9fbc std::__terminate(void (*)()) + 16 7 libc++abi.dylib 0x2139c9f60 std::terminate() + 56 8 libdispatch.dylib 0x1bb11bec0 _dispatch_client_callout + 40 9 libdispatch.dylib 0x1bb11ef8c _dispatch_queue_override_invoke + 788 10 libdispatch.dylib 0x1bb12d944 _dispatch_root_queue_drain + 396 11 libdispatch.dylib 0x1bb12e158 _dispatch_worker_thread2 + 164 12 libsystem_pthread.dylib 0x213a85da0 _pthread_wqthread + 228 13 libsystem_pthread.dylib 0x213a85b7c start_wqthread + 8 12 libsystem_pthread.dylib 0x213a85b7c start_wqthread + 8 My code private func encodeStringTo64(fromString: String) -> String? { let plainData = fromString.data(using: .utf8) return plainData?.base64EncodedString(options: []) } Call foundation method extension Data { ... /// Returns a Base-64 encoded string. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded string. @inlinable public func base64EncodedString(options: Data.Base64EncodingOptions = []) -> String } Description This foundation method don't have throws, but it throw an exception. It will cause a crash.
Posted Last updated
.
Post not yet marked as solved
1 Replies
46 Views
Im using Notions API to print out some data from one of my own pages in notion and im using URLSession to make the request then parsing the unwrapped data but nothing is being returned to my console and I know my endpoint and API key is correct. I've gone through the notion API documentation can't can't seem to find anything in it that I am not doing or doing wrong. Ill provide my code as well as the documentation I've been consulting: https://developers.notion.com/reference/intro import Foundation struct Page: Codable { let id: String let title: String } let endpoint = URL(string: "https://api.notion.com/v1/pages/8efc0ca3d9cc44fbb1f34383b794b817") let apiKey = "… redacted …" let session = URLSession.shared func makeRequest() { if let endpoint = endpoint { let task = URLSession.shared.dataTask(with: endpoint) { data, response, error in if let taskError = error { print("could not establish url request:\(taskError)") return } if let unwrapData = data { //safely unwrapping the data value using if let do { let decoder = JSONDecoder() //JSONDecoder method to decode api data, let codeUnwrappedData = try decoder.decode(Page.self,from: unwrapData) //type: specifies its a struct, from: passes the data parmeter that contains the api data to be decoded } catch { print("could not parse json data") } } if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 200 { if let apiData = data { print(String(data: apiData, encoding: .utf8)!) } } else { print("unsuccessful http response:\(httpResponse)") } makeRequest() } } task.resume() } }
Posted
by Aor1105.
Last updated
.
Post not yet marked as solved
8 Replies
203 Views
I'm getting the following error @main: Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1886cdcf8). It occurs about every other time someone attempts to log in to the app. Also I cannot replicate this issue on the simulator -- only on physical devices.
Posted Last updated
.
Post not yet marked as solved
2 Replies
107 Views
My app always crash when I trying to assign an enum to a value of[String: Any] only on iOS14.6, tested on iOS15, iOS16, iOS17, never saw this issue. The function would pass an ConnectState enum and a serial number string to a userInfo of notification, received class may perform some UI updates when connect state changed. func post(state: ConnectState, serial: Int) { var userInfo: [String: Any] = [:] userInfo["state"] = state userInfo["serial"] = serial print(userInfo) NotificationCenter.default.post(name: NSNotification.Name("PostName"), object: nil, userInfo: userInfo) } @objc enum ConnectState: UInt8 { case connected = 0x00 case disConnected = 0x01 var description: String { switch self { case .connected: return "connected" case .disConnected: return "disConnected" } } } Classes received this notification, may perform some task based on connect state changed. class AClass { init() { NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: NSNotification.Name("PostName"), object: nil) } @objc func handleNotification(_ notification :Notification) { let state = notification.userInfo?["state"] as! ConnectState print("AClass handleNotification: \(state.description)") } } let a = AClass() post(state: .disConnected, serial: 123456) post(state: .connected, serial: 123456) //["serial": 123456, "state": __lldb_expr_3.ConnectState] //AClass handleNotification: disConnected //["serial": 123456, "state": __lldb_expr_3.ConnectState] //AClass handleNotification: connected The crashes always happened in the line that assigning the ConnectState enum to dictionary [String: Any] value, both connect state and serialNumber are not nil or optional. I'm not sure why would this related to a allocate issue, is my code wrong? AppName(645,0x16f61f000) malloc: can't allocate region :*** mach_vm_map(size=1152921504606863360, flags: 100) failed (error code=3) AppName(645,0x16f61f000) malloc: *** set a breakpoint in malloc_error_break to debug ```Since we only have one iOS14.6 device, it will be a challenge to test on other same iOS version device, nor test on simulator.
Posted
by Rimbaud.
Last updated
.
Post marked as solved
6 Replies
106 Views
Hi together, i have truble to parse an json with an array like following: "data": [ [ 0000000000, [ { "count": 0 } ] ], [ 0000000000, [ { "count": 0 } ] ] ], Can someone help me to parse that with the this? Thanks
Posted
by clemens68.
Last updated
.
Post not yet marked as solved
14 Replies
255 Views
I recently re-read Performing manual server trust authentication and noticed that it does not mention having to call SecTrustEvaluate (or its replacements) in client code (anymore). Is that implicitly taken care of by ATS?
Posted
by jzilske.
Last updated
.
Post not yet marked as solved
2 Replies
83 Views
It seems that the first time I open my app after the phone is restarted, the app does not properly access UserDefaults. When my app is launched, I pull relevant user settings / preferences from UserDefaults. I recently noticed (after some users reached out about issues) that the first time the app is opened after a restart, the app appears as though all user settings / preferences have been erased. If the app is force quit and reopened, the user data seems to come back normally. If the user takes action in the app before force quitting, though, UserDefaults will be written to with these new, empty values (essentially erasing what used to be in UserDefaults). This makes it seem as though right after the phone is restarted, the app is unable to pull data from UserDefaults for some reason. Has anyone else seen this issue? It could also be due to the lifecycle of my app and how I access UserDefaults, so if others don't have this issue it would be great to hear how you handle this.
Posted Last updated
.
Post marked as solved
2 Replies
114 Views
I have a repeating timer installed like this: _cmdTimer = [NSTimer timerWithTimeInterval: 0.5 target: self selector: @selector(timedTask:) userInfo: nil repeats: YES]; [NSRunLoop.mainRunLoop addTimer: _cmdTimer forMode: NSModalPanelRunLoopMode]; [NSRunLoop.mainRunLoop addTimer: _cmdTimer forMode: NSDefaultRunLoopMode]; The first time the timer fires, it opens a modal dialog. But then the timer does not fire again until the dialog is closed. I don't get that, since I scheduled the timer in NSModalPanelRunLoopMode. To verify that the dialog was running in that mode, just before opening the dialog I said [self performSelector: @selector(testMe) withObject: nil afterDelay: 0.7 inModes: @[NSModalPanelRunLoopMode] ]; and the testMe method did get executed while the dialog was open.
Posted
by JWWalker.
Last updated
.
Post not yet marked as solved
6 Replies
173 Views
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?
Posted
by Nickkk.
Last updated
.
Post not yet marked as solved
0 Replies
104 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
139 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
344 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
132 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
129 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
132 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
122 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
147 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
.