Construct and manage graphical, event-driven user interfaces for iOS or tvOS apps using UIKit.

UIKit Documentation

Post

Replies

Boosts

Views

Activity

"UIDevice.current.batteryLevel" is always "0" in macOS Sonoma 14.4
I recently updated to macOS Sonoma 14.4 and now UIDevice.current.batteryLevel is always 0. Code to reproduce: import SwiftUI struct ContentView: View { @State private var monitoringEnabled = UIDevice.current.isBatteryMonitoringEnabled; @State private var batteryLevel = UIDevice.current.batteryLevel; var body: some View { VStack { Text("Battery Monitoring Enabled: " + String(monitoringEnabled)) Text("Battery Level: " + String(batteryLevel)) Button("Toggle Monitoring") { monitoringEnabled = !monitoringEnabled; UIDevice.current.isBatteryMonitoringEnabled = monitoringEnabled; batteryLevel = UIDevice.current.batteryLevel; } } .padding() } } Run the above on a macOS 14.4 target, click "Toggle Monitoring", and you'll see battery level is reported as 0: I also see the following error in my app logs when running on macOS 14.4: Error retrieving battery status: result=-536870207 percent=0 hasExternalConnected=1 isCharging=0 isFullyCharged=0 This code displays the expected battery level when running on an actual iOS device:
2
1
751
Mar ’24
"Attempted to dequeue a cell for a different registration or reuse identifier than the existing cell when reconfiguring an item, which is not allowed"
Searching for my very title (including the quotes) generated no results on Google. If you run this UIKit app and tap the right bar button item: class ViewController: UIViewController { var boolean = false { didSet { var snapshot = self.snapshot snapshot.reconfigureItems(snapshot.itemIdentifiers) // if you comment this out the app doesn't crash dataSource.apply(snapshot) } } var snapshot: NSDiffableDataSourceSnapshot<String, String> { var snapshot = NSDiffableDataSourceSnapshot<String, String>() snapshot.appendSections(["main"]) snapshot.appendItems(boolean ? ["one"] : ["one", "two"]) return snapshot } var collectionView: UICollectionView! var dataSource: UICollectionViewDiffableDataSource<String, String>! override func viewDidLoad() { super.viewDidLoad() configureHierarchy() configureDataSource() } func configureHierarchy() { collectionView = .init(frame: .zero, collectionViewLayout: createLayout()) view.addSubview(collectionView) collectionView.frame = view.bounds navigationItem.rightBarButtonItem = .init( title: "Toggle boolean", style: .plain, target: self, action: #selector(toggleBoolean) ) } @objc func toggleBoolean() { boolean.toggle() } func createLayout() -> UICollectionViewLayout { UICollectionViewCompositionalLayout { section, layoutEnvironment in let config = UICollectionLayoutListConfiguration(appearance: .insetGrouped) return NSCollectionLayoutSection.list(using: config, layoutEnvironment: layoutEnvironment) } } func configureDataSource() { let cellRegistration1 = UICollectionView.CellRegistration<UICollectionViewListCell, String> { cell, indexPath, itemIdentifier in } let cellRegistration2 = UICollectionView.CellRegistration<UICollectionViewListCell, String> { cell, indexPath, itemIdentifier in } dataSource = .init(collectionView: collectionView) { [unowned self] collectionView, indexPath, itemIdentifier in if indexPath.row == 0 && boolean { collectionView.dequeueConfiguredReusableCell(using: cellRegistration1, for: indexPath, item: itemIdentifier) } else { collectionView.dequeueConfiguredReusableCell(using: cellRegistration2, for: indexPath, item: itemIdentifier) } } dataSource.apply(self.snapshot, animatingDifferences: false) } } it crashes with that error message. The app uses a collection view with list layout and a diffable data source. It has one section, which should show one row if boolean is true, two if it's false. When boolean changes, the collection view should also reconfigure its items (in my real app, that's needed to update the shown information). If you comment out snapshot.reconfigureItems(snapshot.itemIdentifiers), the app no longer crashes. What's the correct way of reconfiguring the items of a diffable data source then? iOS 17.5, iPhone 15 Pro simulator, Xcode 15.4, macOS 17.5, MacBook Air M1 8GB.
1
0
328
Jun ’24
UIButton.ConfigurationUpdateHandler slow in UITableView cell [UIButton.Configuration, UIButtonConfiguration]
If you run the following UIKit app and tap on the button, you can see that it only updates its color if you hold on it for a bit, instead of immediately (as happens in the second app) (iOS 17.5, iPhone 15 Pro simulator, Xcode 15.4). This app consists of a view controller with a table view with one cell, which has a CheckoutButton instance constrained to its contentView top, bottom, leading and trailing anchors. The checkout button uses UIButton.Configuration to set its appearance, and update it based on its state. import UIKit class ViewController: UIViewController { let tableView = UITableView() let checkoutButton = CheckoutButton() override func viewDidLoad() { super.viewDidLoad() // table view setup view.addSubview(tableView) tableView.frame = view.bounds tableView.autoresizingMask = [.flexibleHeight, .flexibleWidth] tableView.dataSource = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.contentView.addSubview(checkoutButton) checkoutButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ checkoutButton.topAnchor.constraint(equalTo: cell.contentView.topAnchor), checkoutButton.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor), checkoutButton.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor), checkoutButton.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor) ]) return cell } } class CheckoutButton: UIButton { override init(frame: CGRect) { super.init(frame: frame) var configuration = UIButton.Configuration.plain() var attributeContainer = AttributeContainer() attributeContainer.font = .preferredFont(forTextStyle: .headline) attributeContainer.foregroundColor = .label configuration.attributedTitle = .init("Checkout", attributes: attributeContainer) self.configuration = configuration let configHandler: UIButton.ConfigurationUpdateHandler = { button in switch button.state { case .selected, .highlighted: button.configuration?.background.backgroundColor = .systemCyan case .disabled: button.configuration?.background.backgroundColor = .systemGray4 default: button.configuration?.background.backgroundColor = .systemBlue } } self.configurationUpdateHandler = configHandler } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } In this second app, instead, the selection of the button is immediately reflected in its appearance: import UIKit class ViewController: UIViewController { let button = CheckoutButton() override func viewDidLoad() { super.viewDidLoad() view.addSubview(button) button.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ button.centerXAnchor.constraint(equalTo: view.centerXAnchor), button.centerYAnchor.constraint(equalTo: view.centerYAnchor), button.widthAnchor.constraint(equalToConstant: 300), button.heightAnchor.constraint(equalToConstant: 44) ]) } } class CheckoutButton: UIButton { override init(frame: CGRect) { super.init(frame: frame) var configuration = UIButton.Configuration.plain() var attributeContainer = AttributeContainer() attributeContainer.font = .preferredFont(forTextStyle: .headline) attributeContainer.foregroundColor = .label configuration.attributedTitle = .init("Checkout", attributes: attributeContainer) self.configuration = configuration let configHandler: UIButton.ConfigurationUpdateHandler = { button in switch button.state { case .selected, .highlighted: button.configuration?.background.backgroundColor = .systemCyan case .disabled: button.configuration?.background.backgroundColor = .systemGray4 default: button.configuration?.background.backgroundColor = .systemBlue } } self.configurationUpdateHandler = configHandler } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } This app consists of a view controller with just a button: no table view unlike in the first app. How do I make the button show its selection as soon as it's tapped, no matter if it's in a table view cell or on its own?
1
0
221
Jun ’24
XCUIElement with zero frame but showing.
I have a bug I am writing a UI Test for and I am struggling to find a way to test the fixed UI vs the buggy UI. In the buggy version, the UI element is visible on the screen but has a 0,0 width and height. It's visible because it's not set to 'clip to bounds', so it's overlaying the rest of my UI. The app sets the element to be hidden in certain situations and I wanted to make sure in my test, that it's not on the screen in that situation. The problem is that .exists returns true in both situations (.hidden == true, .hidden == false), and .isHittable always returns false because its either no on the screen at all or has a 0,0 width, height. So I can't use .exists; I can't use .isHittable; and I can't use the .frame either. Is there simply a way to check if it's actually visible?
1
0
266
Jun ’24
[iOSAppOnMac] ShareKit: Crashes in SHKItemIsPDF() or -[SHKSaveToFilesSharingService saveFileURL:completion:]
I have a custom document-based iOS app that also runs on macOS. After implementing -activityItemsConfiguration to enable sharing from the context menu, I found that the app crashes on macOS when selecting Share… from the context menu and then selecting Save (i.e. Save to Files under iOS). This problem does not occur on iOS, which behaves correctly. - (id<UIActivityItemsConfigurationReading>)activityItemsConfiguration { NSItemProvider * provider = [[NSItemProvider alloc] initWithContentsOfURL:self.document.presentedItemURL]; UIActivityItemsConfiguration * configuration = [UIActivityItemsConfiguration activityItemsConfigurationWithItemProviders:@[ provider ]]; // *** crashes with com.apple.share.System.SaveToFiles return configuration; } Additionally, I found that to even reach this crash, the workaround implemented in the NSItemProvider (FBxxx) category of the sample project is needed. Without this, the app will crash much earlier, due to SHKItemIsPDF() erroneously invoking -pathExtension on an NSItemProvider. This appears to be a second bug in Apple’s private ShareKit framework. #import <UniformTypeIdentifiers/UniformTypeIdentifiers.h> @implementation NSItemProvider (FBxxx) // *** SHKItemIsPDF() invokes -pathExtension on an NSItemProvider (when running under macOS, anyway) -> crash - (NSString *)pathExtension { return self.registeredContentTypes.firstObject.preferredFilenameExtension; } @end Again, this all works fine on iOS (17.5) but crashes when the exact same app build is running on macOS (14.5). I believe these bugs are Apple's. Any idea how to avoid the crash? Is there a way to disable the "Save to Files" option in the sharing popup? I filed FB13819800 with a sample project that demonstrates the crash on macOS. I was going to file a TSI to get this resolved, but I see that DTS is not responding to tech support incidents until after WWDC.
0
0
192
Jun ’24
How to: Compositional layout with self-sizing rows of N columns where the height of each item is set to the tallest item in its row
Paging Steve Breen! 😄 I've seen this question asked a zillion times but I've never seen an answer. Is it possible to configure compositional layout to give you a grid of N columns (say 2 or 3) where each item in each row/group self-size their height, but the heights of those items are then set to be the height of the tallest item in their row. This is easy to do if you ignore the self-sizing requirement (just use a fixed or absolute item height), but on the surface this doesn't even appear to be possible if you require self-sizing. What I've Tried Configuring a layout where the items are set to a fractional height of 1.0 and their group is set to an estimated height (ex: 100). I was hoping compositional layout would interpret this as, "Please self-size the height of the group and make each item 100% of that height." Unfortunately, compositional layout just uses the estimate you provide for the height as the actual height and no self-sizing occurs at all. Sad panda. 🐼 Use visibleItemsInvalidationHandler to attempt to identify which items share a row and reset their heights to be the height of the tallest item in that row. Sadly, the handler doesn't really have access to the data it needs to do this, nor is it allowed to change frames, nor is it called on the first layout pass, nor does it appear to be supported at all for layouts containing estimated items. In fact, if you try to use it with layouts that support self-sizing, you'll get this error message: [UICompositionalLayout] note: the section invalidation handler cannot currently mutate visible items for layouts containing estimated items. Please file an enhancement request on UICollectionView. Wishing upon a star. Oh, and I also filed a radar asking: FB11776888 Here's a visual aid: I have a little test program as well, but unfortunately I can't upload it here. Happy to share if it would be helpful. Here are a couple snippets: #1 // This doesn't work     private func makeLayout1() -> UICollectionViewCompositionalLayout {         // Item         let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5), heightDimension: .fractionalHeight(1))         let item = NSCollectionLayoutItem(layoutSize: itemSize)         // Group         let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(100))         let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, repeatingSubitem: item, count: 2)         group.interItemSpacing = .fixed(10)         // Section         let section = NSCollectionLayoutSection(group: group)         return UICollectionViewCompositionalLayout(section: section)     } #2 // This self-sizes the heights of the items, but allows the items in each row to be different heights rather than providing any way to constrain them to the height of the tallest self-sized item in each row     private func makeLayout2() -> UICollectionViewCompositionalLayout {         // Item         let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5), heightDimension: .estimated(100))         let item = NSCollectionLayoutItem(layoutSize: itemSize)         // Group         let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(100))         let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, repeatingSubitem: item, count: 2)         group.interItemSpacing = .fixed(10)         // Section         let section = NSCollectionLayoutSection(group: group)         return UICollectionViewCompositionalLayout(section: section)     } Options? My guess is that compositional layout simply doesn't support layouts that require a "partial second pass" per group, where the frames of the items can be updated based on information collected during self-sizing the other items in the group (to, for example, force them all to a common height, or align them top/bottom/centered within their group). If that's the case (not supported), I would love a suggestion for where I might override the layout to provide this capability. Thank you! ❤️
4
5
3.4k
Nov ’22
Disable the keyboard suggestions for a UITextField
I have a UITableView with a bunch of UITextFields in 'em. (in a custom UITableViewCell subclass) For every UITextField I have set: cell.textField.textContentType = .none I even tried: cell.textField.inlinePredictionType = .no // iOS >= 17 and: cell.textField.keyboardType = .default cell.textField.autocorrectionType = .no cell.textField.spellCheckingType = .no cell.textField.autocapitalizationType = .none Still, when I tap in one of them, I get a 'suggestion' in a bar just above the Keyboard that I can fill in my phone number. How can I prevent that? I am using: xcode 15.4, iOS 17.5.1. Compiling for iOS 13.0 and later.
2
0
357
May ’24
strange behavior when App Lifecycle Events on an iPhone 15 Pro Max when turning off the screen using the side button in iOS 17.5.1
Hello fellow iOS developers! Using a simple app with only print lines in the SceneDelegate class, all other tested devices running iOS 17.5.1 (iPad Pro M4, iPad Pro 3rd Generation, iPhone XR) exhibit this behavior when turning off the screen using the side button: 2024-05-31 21:21:13.0260 --sceneWillResignActive 2024-05-31 21:21:13.0290 --sceneDidEnterBackground This is the same as when putting the app in the background. However, the iPhone 15 Pro Max running iOS 17.5.1 does this: 2024-05-31 9:08:28.4580 PM --sceneWillResignActive 2024-05-31 9:08:29.8310 PM --sceneDidBecomeActive 2024-05-31 9:08:29.8490 PM --sceneWillResignActive 2024-05-31 9:08:29.8510 PM --sceneDidEnterBackground I’ve also submitted this as a potential bug in the Feedback Assistant. Does anyone know why sceneDidBecomeActive() is invoked when turning off the screen with the side button in this specific case? I’m aware that using Face ID causes the app to briefly experience sceneDidBecomeActive() followed by sceneWillResignActive() during biometric authentication, and then switches back to sceneDidBecomeActive() once authentication completes. But why does this odd behavior occur when turning the screen off in simple app? Is there a way to detect that the side button has been pressed to turn off the screen? Thank you in advance, --SalCat
1
1
222
Jun ’24
How to set timeFormat of DatePicker in swift
DatePicker always get timeFormat from device setting, but i need to show time in datePicker based on My app setting not device setting. any solution for this problem I tried to set locale "us_POSIX" locale for 12 hour and "us_GB" for 24 hour format this way is work in gregorian calendar , but in japanese calendar not showing year properly like (picker showing " 6 " instead of " Reiwa 6 " )
4
0
370
May ’24
UIDocumentPickerViewController -> OneDrive/G-Drive -> NSFileCoordinator
Hey, I'm not sure I'm even in the correct ballpark - trying to allow my app to download largish videos from user's OneDrive and G-Drive to app Is it correct to use NSFileCoordinator in this way? How do I report progress as it downloads the video (is it possible?) Is it correct to dismiss the picker like this? anything else wrong (or, like is....any of it correct? :) it's sort of working with my contrived examples (I created new personal G-drive / Onedrive accounts, and copied vids up there), but...when I use a file from our corporate OneDrive, from shared folder, I get: "NSCocoaErrorDomain Code=3328 "The requested operation couldn’t be completed because the feature is not supported." Is this the NSFileProvider extension (Microsoft's) complaining? public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {     guard  let url = urls.first else {       return     }     let isSecurityScoped = url.startAccessingSecurityScopedResource()     print("(#function) - iSecurityScoped = (isSecurityScoped)")     print("(#function) - document at (url)")     let filename = String(UUID().uuidString.suffix(6)) + "_" +  url.lastPathComponent     let newURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(filename)          let readingIntent = NSFileAccessIntent.readingIntent(with: url, options: .withoutChanges)     fileCoordinator.coordinate(with: [readingIntent], queue: queue) { error in       defer {         if isSecurityScoped {           url.stopAccessingSecurityScopedResource()         }       }       if let error = error {         print("(#function) - (error)")         return       }       let safeURL = readingIntent.url       do {         let fileData = try Data(contentsOf: safeURL)         try fileData.write(to: newURL, options: .atomic)         print("(#function) - SUCCESS - newURL = (newURL)")       } catch {         print("(#function) - NOOOOO - (error)")       }     }     controller.dismiss(animated: true)   }
1
1
633
Aug ’22
Issues with playing 3D videos and adding additional views in VisionOs AvplayerViewController
I want to add additional UI to places outside of AVPlayerViewController, such as adding likes and comments, but I found that once AVPlayerViewController is wrapped in other views, it becomes inline mode and cannot play 3D effects, instead becoming 2D effects. 3D effects can only be played when it is full screen. I want to know if there is any way to meet my needs like this? On the premise of being able to play 3D videos, add additional layouts outside the AVPlayerViewController, or use AVPlayerViewController to achieve the method of both playing 3D videos and adding additional layouts outside the player. If anyone knows, could you give me some guidance? Thank you.
0
1
290
Jun ’24
Adding in-app browser - browser never spawns in view.
Preamble: I am creating an iOS build of a Ren'Py game. My coding experience with Swift/ObjC is nearly nonexistent and I've primarily followed tutorials up to this point. Ren'Py uses an underlying framework to create an Xcode project. I do not have control over how this framework does things, but I can add files before actually compiling inside Xcode. I MUST use the pyobjus library to do so based on my current understanding, abilities, and frameworks. The included IAPHelper class processes in-app purchasing and it works great! The following function indicates, however, that there is a rootViewController that I need to attach to. - (void) showDialog { if (alert != nil) { return; } alert = [UIAlertController alertControllerWithTitle:self.dialogTitle message:nil preferredStyle:UIAlertControllerStyleAlert ]; UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleLarge]; // Adjust the indicator so it is up a few pixels from the bottom of the alert indicator.center = CGPointMake(alert.view.bounds.size.width / 2, alert.view.bounds.size.height - 50); [indicator startAnimating]; [alert.view addSubview: indicator]; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated" [UIApplication.sharedApplication.keyWindow.rootViewController presentViewController:alert animated:YES completion:nil]; #pragma clang diagnostic pop } Problem: I am TRYING to implement an in-app browser for Patreon authentication purposes. The files I have put together are as follows: BrowserViewController.h // BrowserViewController.h #import <UIKit/UIKit.h> #import <WebKit/WebKit.h> @interface BrowserViewController : UIViewController - (void)loadURL:(NSString *)urlString; @end BrowserViewController.m // BrowserViewController.m #import "BrowserViewController.h" @interface BrowserViewController () @property (nonatomic, strong) WKWebView *webView; @end @implementation BrowserViewController - (void)viewDidLoad { [super viewDidLoad]; self.webView = [[WKWebView alloc] initWithFrame:self.view.frame]; [self.view addSubview:self.webView]; NSLog(@"viewDidLoad"); } - (void)loadURL:(NSString *)urlString { NSURL *url = [NSURL URLWithString:urlString]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [self.webView loadRequest:request]; NSLog(@"loadURL"); } @end OAuth2Strategy.py init python in auth: from urllib.parse import urlencode, urlparse, parse_qs from urllib.request import urlopen, Request import ssl import certifi from store import webserver, OpenURL import json class OAuth2Strategy(): def __init__(self, authorization_url, token_url, client_id, client_secret, callback_url, scope): self.authorization_url = authorization_url self.token_url = token_url self.client_id = client_id self.client_secret = client_secret self.callback_url = callback_url self.scope = scope self.on_success_callback = None self.on_fail_callback = None def run(self, on_success_callback = None, on_fail_callback = None): self.on_success_callback = on_success_callback self.on_fail_callback = on_fail_callback webserver.start(self) if renpy.renpy.ios: from pyobjus import autoclass, objc_str # Import the Objective-C class BrowserViewController = autoclass('BrowserViewController') # Create an instance of the BrowserViewController browser = BrowserViewController.alloc().init() # Load a URL url = self.make_authorize_url() browser.loadURL_(objc_str(url)) elif renpy.renpy.android: pass else: renpy.run(OpenURL(self.make_authorize_url())) def make_authorize_url(self): return self.authorization_url + "?client_id={client_id}&scope={scope}&redirect_uri={redirect_uri}&response_type=code".format( client_id=self.client_id, scope=self.scope, redirect_uri=self.redirect_uri, ) @property def redirect_uri(self): return "http://127.0.0.1:" + str(webserver.PORT) + self.callback_url def handle_auth(self, request): parsed_path = urlparse(request.path) query = parse_qs(parsed_path.query) code = query.get("code") if not code: request.send_response(400) request.send_header('Content-type', 'text/html') request.end_headers() request.wfile.write(b'Failed to authenticate. You can now close this window.') webserver.stop() if self.on_fail_callback: self.on_fail_callback() return code = code[0] tokens = self.get_tokens(code) request.send_response(200) request.send_header('Content-type', 'text/html') request.end_headers() request.wfile.write(b'Success! You can now close this window.') webserver.stop() if self.on_success_callback: self.on_success_callback(tokens) def get_tokens(self, code): ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH, cafile=certifi.where()) data = urlencode({ "grant_type": "authorization_code", "code": code, "client_id": self.client_id, "client_secret": self.client_secret, "redirect_uri": self.redirect_uri, }).encode("utf-8") headers = {"Content-Type": "application/x-www-form-urlencoded"} req = Request(self.token_url, data=data, headers=headers, method="POST") response = urlopen(req, context=ctx) data = response.read().decode("utf-8") data = json.loads(data) return data If I use the default OpenURL function Safari opens as the full blown browser rather than in-app, hence why I am trying to override it. When I run my app and click the button that SHOULD spawn the browser, nothing happens. I can see that my URL is getting pushed to the function in the log along with Warning: -[BETextInput attributedMarkedText] is unimplemented and Failed to request allowed query parameters from WebPrivacy. though my admittedly light research indicates this isn't an issue. I have a feeling I'm not attaching my webView to the right hierarchy but I'm not sure exactly what I'm doing wrong.
1
0
295
May ’24
UIActivityViewController.excludeActivityTypes does not work sometimes
I call a share sheet from React Native. It's seemingly working fine. But excludeActivityTypes may not work properly after the second time. What's wrong with my code? Sorry for my poor English. @objc(NativeModuleShare) class NativeModuleShare: NSObject, RCTBridgeModule { static func moduleName() -> String!{ return "NativeModuleShare"; } static func requiresMainQueueSetup () -> Bool { return true; } @objc func ShowShareSheet(_ title:String, message:String, url:String)->Void { let itemSource = ShareActivityItemSource(shareImage: UIImage(named: "logoBgWhite")!, shareText: message, shareTitle: title, shareUrl: url) let activityVC = UIActivityViewController(activityItems: [itemSource, itemSource.shareText], applicationActivities: nil) let excludeActivityTypes = [ UIActivity.ActivityType.postToTwitter, UIActivity.ActivityType.postToFacebook ] activityVC.excludedActivityTypes = excludeActivityTypes; DispatchQueue.main.async { (UIApplication.shared.delegate as? AppDelegate)?.window.rootViewController?.present(activityVC, animated: true, completion: nil); } } }
0
0
171
May ’24
Asking about Viewcontroller presenter
I have a ViewController A that need to present in Viewcontroller B. But before the VC A is presented, user pushed to Viewcontroller C and the VC A still show on C. How can it possible? In my point of view, I think the VC B will not show because the VC A is hided. Anyone can help me with this?. Many thanks
0
0
211
May ’24
Scheduling Local Notifications with repeat interval
I am building an application where I need to implement a use case where a local notification is set for a specific date / time (e.g 05/6/24 8 PM) to display to the user (e.g. "Take your Meds") and I want him to continue to get that alert every X minutes (e.g. every 2 minutes) until I cancel it (e.g. when the user indicates he has taken his medicene). NOTE: I do NOT want to rely on push notifications from the server for doing the reminders because it needs to work when the device is off the network (like on a plane or a cruise ship in the middle of the ocean or whatever). This would seem to be a pretty common use case, but looking at the previous and existing local notification frameworks, I only see the option to create a calendar based trigger with a boolean repeat (UNCalendarNotificationTrigger) or a time interval based trigger with a boolean repeat (UnTimeIntervalNotificationTrigger), but nothing that combines these in a way that allows me to implement the above stated use case.
1
0
252
May ’24
UITableView setTableHeaderView
我遇到了一个问题,当一个View是tableview的tableHeaderview时,我把View重新嵌套一层重新设置给tableHeaderview,这个View不展示 代码如下: UIView *view = [UIView new]; tableView.tableHeaderview = view; UiView *otherView = [UIview new]; otherView addSubview:view]; tableView.tableHeaderview = otherView; 这个时候view不展示了。 根据调用栈看,设置tableHeaderview后,view执行了一次removeFromSuperview,从otherView中消失了。 所以想了解一下,当设置新的tableHeaderview,对旧的HeaderView是怎么处理的?
1
0
237
May ’24
Crash in [UIViewController _presentViewController:withAnimationController:completion:]
Our app has a Crash, here is the Crash report. How should I investigate this error? Fatal Exception: NSInvalidArgumentException 0 CoreFoundation 0x9e48 __exceptionPreprocess 1 libobjc.A.dylib 0x178d8 objc_exception_throw 2 UIKitCore 0x326cbc -[UIViewController _presentViewController:withAnimationController:completion:] 3 UIKitCore 0x325c10 __63-[UIViewController _presentViewController:animated:completion:]_block_invoke 4 UIKitCore 0x349598 -[_UIViewControllerTransitionCoordinator _applyBlocks:releaseBlocks:] 5 UIKitCore 0x2b7a48 -[_UIViewControllerTransitionContext _runAlongsideCompletions] 6 UIKitCore 0x2b6ad8 -[_UIViewControllerTransitionContext completeTransition:] 7 UIKitCore 0x2b7c38 -[UITransitionView notifyDidCompleteTransition:] 8 UIKitCore 0x2b7838 -[UITransitionView _didCompleteTransition:] 9 UIKit 0xa7e58 -[UITransitionViewAccessibility _didCompleteTransition:] 10 UIKitCore 0x103d464 __UIVIEW_IS_EXECUTING_ANIMATION_COMPLETION_BLOCK__ 11 UIKitCore 0xd14ac -[UIViewAnimationBlockDelegate _didEndBlockAnimation:finished:context:] 12 UIKitCore 0xd0408 -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] 13 UIKitCore 0xcfb28 -[UIViewAnimationState animationDidStop:finished:] 14 UIKit 0xb0f50 -[UIViewAnimationStateAccessibility animationDidStop:finished:] 15 UIKitCore 0xcfc3c -[UIViewAnimationState animationDidStop:finished:] 16 UIKit 0xb0f50 -[UIViewAnimationStateAccessibility animationDidStop:finished:] 17 QuartzCore 0x1310c CA::Layer::run_animation_callbacks(void*) 18 libdispatch.dylib 0x3fdc _dispatch_client_callout 19 libdispatch.dylib 0x127f4 _dispatch_main_queue_drain 20 libdispatch.dylib 0x12444 _dispatch_main_queue_callback_4CF 21 CoreFoundation 0x9a6d8 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ 22 CoreFoundation 0x7c03c __CFRunLoopRun 23 CoreFoundation 0x80ec0 CFRunLoopRunSpecific 24 GraphicsServices 0x1368 GSEventRunModal 25 UIKitCore 0x3a186c -[UIApplication _run] 26 UIKitCore 0x3a14d0 UIApplicationMain 27 Authenticator 0x9334 main + 26 (AppDelegate.swift:26) 28 ??? 0x1b65de960 (シンボルが不足しています)
4
2
959
Jan ’23
Swift Playgrounds 4.1 keeps crashing when rerunning code
Try to learn some Swift coding but Playgrounds keeps crashing. I run Playgrounds 4.1 on latest Monterey 12.7.5, from a MacBook Air dated back 2017. Part of the error log says: Thread 9 Crashed:: Dispatch queue: com.apple.UIKit._UIViewServiceInterfaceConnectionRequest com.apple.PlaygroundsMac.ExecutionExtension The error can be reproduced by re-running the code; Everything goes well when the code was run at first time, but is doomed to fail at second run. Any help?
0
0
297
May ’24
ios app crash
This is crash stack. What caused this crash? How to solve it? Date/Time: 2024-05-17 11:12:48.0370 +0800 Launch Time: 2024-05-17 11:12:28.4598 +0800 OS Version: iPhone OS 17.4.1 (21E236) Release Type: User Baseband Version: 3.50.04 Report Version: 104 Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x00000001aee09920 Triggered by Thread: 0 Kernel Triage: VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter Thread 0 Crashed: 0 libdispatch.dylib 0x00000001aee09920 _dispatch_lane_resume + 712 (queue.c:3284) 1 CoreFoundation 0x00000001a6f357a8 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 (CFNotificationCenter.c:700) 2 CoreFoundation 0x00000001a6f35170 ___CFXRegistrationPost_block_invoke + 88 (CFNotificationCenter.c:193) 3 CoreFoundation 0x00000001a6f350b8 _CFXRegistrationPost + 440 (CFNotificationCenter.c:221) 4 CoreFoundation 0x00000001a6f34608 _CFXNotificationPost + 728 (CFNotificationCenter.c:1247) 5 Foundation 0x00000001a5dc6f10 -[NSNotificationCenter postNotificationName:object:userInfo:] + 92 (NSNotification.m:531) 6 UIKitCore 0x00000001a930f04c -[UIApplication _sendWillEnterForegroundCallbacks] + 212 (UIApplication.m:11709) 7 UIKitCore 0x00000001a930d7cc __101-[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:]_block_invoke_2 + 1272 (_UISceneLifecycleMultiplexer.m:653) 8 UIKitCore 0x00000001a930d298 _UIScenePerformActionsWithLifecycleActionMask + 112 (_UISceneLifecycleState.m:109) 9 UIKitCore 0x00000001a9393934 __101-[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:]_block_invoke + 216 (_UISceneLifecycleMultiplexer.m:566) 10 UIKitCore 0x00000001a92bcac4 -[_UISceneLifecycleMultiplexer _performBlock:withApplicationOfDeactivationReasons:fromReasons:] + 220 (_UISceneLifecycleMultiplexer.m:515) 11 UIKitCore 0x00000001a92bb53c -[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:] + 608 (_UISceneLifecycleMultiplexer.m:565) 12 UIKitCore 0x00000001a92baea4 -[_UISceneLifecycleMultiplexer uiScene:transitionedFromState:withTransitionContext:] + 248 (_UISceneLifecycleMultiplexer.m:468) 13 UIKitCore 0x00000001a92bad74 __186-[_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction _performActionsForUIScene:withUpdatedFBSScene:settingsDiff:fromSettings:transitionContext:lifecycleActionType:]_block... + 148 (_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction.m:73) 14 UIKitCore 0x00000001a92bac7c +[BSAnimationSettings(UIKit) tryAnimatingWithSettings:fromCurrentState:actions:completion:] + 736 (BSAnimationSettings+UIKit.m:54) 15 UIKitCore 0x00000001a92ba504 _UISceneSettingsDiffActionPerformChangesWithTransitionContextAndCompletion + 224 (_UISceneSettingsDiffAction.m:27) 16 UIKitCore 0x00000001a92ba1b4 -[_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction _performActionsForUIScene:withUpdatedFBSScene:settingsDiff:fromSettings:transitionContext:lifecycleActionType:] + 316 (_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction.m:58) 17 UIKitCore 0x00000001a964ae20 __64-[UIScene scene:didUpdateWithDiff:transitionContext:completion:]_block_invoke.226 + 612 (UIScene.m:2067) 18 UIKitCore 0x00000001a92b9328 -[UIScene _emitSceneSettingsUpdateResponseForCompletion:afterSceneUpdateWork:] + 216 (UIScene.m:1736) 19 UIKitCore 0x00000001a92b9198 -[UIScene scene:didUpdateWithDiff:transitionContext:completion:] + 244 (UIScene.m:2026) 20 UIKitCore 0x00000001a92b8fd8 -[UIApplicationSceneClientAgent scene:handleEvent:withCompletion:] + 336 (UIApplicationSceneClientAgent.m:86) 21 FrontBoardServices 0x00000001bfaeb524 -[FBSScene updater:didUpdateSettings:withDiff:transitionContext:completion:] + 660 (FBSScene.m:812) 22 FrontBoardServices 0x00000001bfaeb270 __94-[FBSWorkspaceScenesClient _queue_updateScene:withSettings:diff:transitionContext:completion:]_block_invoke_2 + 152 (FBSWorkspaceScenesClient.m:692) 23 FrontBoardServices 0x00000001bfaeb10c -[FBSWorkspace _calloutQueue_executeCalloutFromSource:withBlock:] + 168 (FBSWorkspace.m:411) 24 FrontBoardServices 0x00000001bfaeb028 __94-[FBSWorkspaceScenesClient _queue_updateScene:withSettings:diff:transitionContext:completion:]_block_invoke + 344 (FBSWorkspaceScenesClient.m:691) 25 libdispatch.dylib 0x00000001aee02dd4 _dispatch_client_callout + 20 (object.m:576) 26 libdispatch.dylib 0x00000001aee0686c _dispatch_block_invoke_direct + 288 (queue.c:511) 27 FrontBoardServices 0x00000001bfae7490 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 52 (FBSSerialQueue.m:285) 28 FrontBoardServices 0x00000001bfae7410 -[FBSMainRunLoopSerialQueue _targetQueue_performNextIfPossible] + 240 (FBSSerialQueue.m:309) 29 FrontBoardServices 0x00000001bfae72e8 -[FBSMainRunLoopSerialQueue _performNextFromRunLoopSource] + 28 (FBSSerialQueue.m:322) 30 CoreFoundation 0x00000001a6f3d62c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 (CFRunLoop.c:1957) 31 CoreFoundation 0x00000001a6f3c8a8 __CFRunLoopDoSource0 + 176 (CFRunLoop.c:2001) 32 CoreFoundation 0x00000001a6f3b058 __CFRunLoopDoSources0 + 244 (CFRunLoop.c:2038) 33 CoreFoundation 0x00000001a6f39d88 __CFRunLoopRun + 828 (CFRunLoop.c:2955) 34 CoreFoundation 0x00000001a6f39968 CFRunLoopRunSpecific + 608 (CFRunLoop.c:3420) 35 GraphicsServices 0x00000001eb22f4e0 GSEventRunModal + 164 (GSEvent.c:2196) 36 UIKitCore 0x00000001a93acedc -[UIApplication _run] + 888 (UIApplication.m:3692) 37 UIKitCore 0x00000001a93ac518 UIApplicationMain + 340 (UIApplication.m:5282) 38 VRCapture 0x00000001045ac3a4 main + 84 (main.m:33) 39 dyld 0x00000001ca45ad84 start + 2240 (dyldMain.cpp:1298)
0
0
269
May ’24