I am facing same issue with major crash while coming out from this function.
Basically using collectionView.dequeReusableCell with size calculation.
func getSizeOfFavouriteCell(_ collectionView: UICollectionView, at indexPath: IndexPath, item: FindCircleInfoCellItem) -> CGSize { guard let dummyCell = collectionView.dequeueReusableCell( withReuseIdentifier: TAButtonAddCollectionViewCell.reuseIdentifier, for: indexPath) as? TAButtonAddCollectionViewCell else { return CGSize.zero }
dummyCell.title = item.title
dummyCell.subtitle = item.subtitle
dummyCell.icon = item.icon
dummyCell.layoutIfNeeded()
var targetSize = CGSize.zero
if viewModel.favoritesDataSource.isEmpty.not,
viewModel.favoritesDataSource.count > FindSheetViewControllerConstants.minimumFavoritesToDisplayInSection {
targetSize = CGSize(width: collectionView.frame.size.width / 2, height: collectionView.frame.height)
var estimatedSize: CGSize = dummyCell.systemLayoutSizeFitting(targetSize)
if estimatedSize.width > targetSize.width {
estimatedSize.width = targetSize.width
}
return CGSize(width: estimatedSize.width, height: targetSize.height)
}
}
We have resolve issue with size calculation with checking nil. Working fine in xcode 15 and 16+.
Note: Please help me with reason of crash? Is it because of xCode 16.2 onwards **strict check on UICollectionView **
Explore the various UI frameworks available for building app interfaces. Discuss the use cases for different frameworks, share best practices, and get help with specific framework-related questions.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I am creating an application that uses VNDetectBarcodesRequest to read QR codes from images and adjust the image orientation to match that of the QR code finder pattern.
The QR code was successfully read, and the coordinates of the QR code were obtained.Upon checking the obtained topLeft, topRight, and bottomLeft coordinates, they always seem to match the topLeft, topRight, and bottomLeft coordinates of the finder pattern.
Is it specified that the coordinates of topLeft, topRight, and bottomLeft obtained with VNDetectBarcodesRequest match the topLeft, topRight, and bottomLeft of the finder pattern? Or do they just happen to match?
I would appreciate it if you could tell me if the matching of coordinates is a specification.
Thank you for your help.
I want record screen in my app,the method startCaptureWithHandler:completionHandler:,the sampleBuffer, It is supposed to exist but it has become nil.Not only that,but there‘s another problem,when I want to stop recording and save the video,I will check [RPScreenRecorder sharedRecorder].recording first, it will be false sometime,that problems are unusual in iOS 18.3.2 iPhoneXs Max,and unexpected,here is my code
-(void)startCaptureScreen {
NSLog(@"AKA++ startCaptureScreen");
if ([[RPScreenRecorder sharedRecorder] isRecording]) {
return;
}
//屏幕录制
[[RPScreenRecorder sharedRecorder]setMicrophoneEnabled:YES];
NSLog(@"AKA++ MicrophoneEnabled AAAA startCaptureScreen");
[[RPScreenRecorder sharedRecorder]setCameraEnabled:YES];
[[RPScreenRecorder sharedRecorder] startCaptureWithHandler:^(CMSampleBufferRef _Nonnull sampleBuffer, RPSampleBufferType bufferType, NSError * _Nullable error) {
if(self.assetWriter == nil){
if (self.AVAssetWriterStatus == 0) {
[self setupAssetWriterAndStartWith:sampleBuffer];
}
}
if (self.AVAssetWriterStatus != 2) {
return;
}
if (error) {
// deal with error
return;
}
if (self.assetWriter.status != AVAssetWriterStatusWriting) {
[self assetWriterAppendSampleBufferFailWith:bufferType];
return;
}
if (bufferType == RPSampleBufferTypeVideo) {
if(self.assetWriter.status == 0 ||self.assetWriter.status > 2){
} else if(self.videoAssetWriterInput.readyForMoreMediaData == YES){
BOOL success = [self.videoAssetWriterInput appendSampleBuffer:sampleBuffer];
}
}
if (bufferType == RPSampleBufferTypeAudioMic) {
if(self.assetWriter.status == 0 ||self.assetWriter.status > 2){
} else if(self.audioAssetWriterInput.readyForMoreMediaData == YES){
BOOL success = [self.audioAssetWriterInput appendSampleBuffer:sampleBuffer];
}
}
} completionHandler:^(NSError * _Nullable error) {
//deal with error
}];
}
and than ,when want to save it :
-(void)stopRecording {
if([[RPScreenRecorder sharedRecorder] isRecording]){
// The problem is sporadic,recording action failed,it makes me confused
}
[[RPScreenRecorder sharedRecorder] stopCaptureWithHandler:^(NSError * _Nullable error) {
if(!error) {
//post message
}
}];
}
I'm getting the following error Error Domain=com.google.GIDSignIn Code=-4. How do I find out what I'm missing with my setup of Google Cloud?
Topic:
UI Frameworks
SubTopic:
SwiftUI
WKWebView cannot load and display HTTP image resources
Topic:
UI Frameworks
SubTopic:
UIKit
Hi,
I am developing a new SwiftUI app. Running under OSX, I see very high cpu usage (I am generating lots of gpu based updates which shouldn't affect the cpu).
I have used the profiler to ensure my swift property updates are minimal, yet the cpu usage is high coming from SwiftUI.
It seems the high cpu usage is coming from NSAppearance, specifically, CUICopyMeasurements - for a single button??? But the swift updates don't show any buttons being updating
Topic:
UI Frameworks
SubTopic:
SwiftUI
Using the new floating tab bar with ios18 on ipad with an RTL language, when the tabbar is correctly flipped and the right buttons become left buttons, the buttons are pushed off the screen on initial load but do come back after some navigating / reloading, have recreated in a fresh project.
I have an app that run Monte Carlo simulations. I run thousands of simulations in the app and a simulation runs can take on the order of 30 seconds to a minute to complete. I would like to have a progress view that tracks the number of simulation runs. How can I implement this in swiftui?
I have a UITextView being added at runtime to a UIImageView as the result of doing text recognition. It's set to be editable = NO and selectable = YES. When I set the text and select it, it asks the delegate for the menu to display via:
textView:editMenuForTextInRange:suggestedActions:
The suggested items contains many UIAction and UICommand objects that have private methods or do not have the destructive attribute set, yet they are destructive. Some of these are:
promptForReplace:
transliterateChinese:
_insertDrawing:
_showTextFormattingOptions:
I need to return a menu that has only non-destructive commands in it.
First, why isn't UITextView sending only non-destructive suggested commands when its editable is NO?
Second, how can I filter the array of suggested commands when it's impossible to know if they're destructive (as some are missing that attribute)?
In addition to that, even non-destructive commands are causing an unrecognized selector exception, such as the Speak command, which it is sending to my view controller instead of to the UITextView, which is the only thing that knows what the text is that it should speak.
Topic:
UI Frameworks
SubTopic:
UIKit
Hey, I've been having a problem with scroll views in combination with the .geometryGroup() modifier.
I have filed a Feedback (FB17698293) but I also wanted to post this here in case someone maybe has a better workaround for the problem.
Problem
Whenever you conditionally insert a ScrollView inside a VStack that is modified with a .geometryGroup() modifier, the scroll view content offset resets itself after the insertion animation is done, even if you started scrolling inside the scroll view during the animation and haven't let go of the screen. This happens consistently and is fully reproducible (see below), both using a simulator and a real device.
Unfortunately, this is a very annoying glitch that ruins a lot of cool UX components that rely on .geometryGroup().
The weird thing is that the glitch entirely disappears, if you add a simple, non-zero (but greater than 1) .padding() modifier to the VStack (.padding().geometryGroup()).
I have no idea why this fixes the glitch, but it does. However, adding a padding is not feasible in many situations, so this workaround is not ideal.
Steps to reproduce
Launch the code below (using a simulator or a real device) and tap "Toggle Expansion" to insert the scroll view.
As the view is animating in, drag the scroll content and hold it scrolled away from the top.
Wait for the animation to complete. The scroll view will reset the content offset, even though the drag gesture is still active (i.e. you haven't lifted your finger to release the scroll view)
On a real device, this sometimes even leads to an even worse visual artifact where the scroll view is rendered twice for a few frames; once with the correct offset, and once with the reset offset.
I wanted to include a link to a gif/video showing the glitch, but it tells me that imgur is not allowed on the forums.
Expected Behavior
I want the scroll view to respect the content offset, even if I started changing it mid-animation.
Xcode Version
I am using Xcode 16.4 (16F6) but this problem has been occurring since the .geometryGroup() modifier has been release. I was only now able to pinpoint this problem exactly, so I'm filing this feedback.
Code
The entire code that reproduces the problem:
import SwiftUI
struct ContentView: View {
@State private var isExpanded: Bool = false
var body: some View {
VStack {
if isExpanded {
ScrollView {
Text(loremIpsum)
}
}
Button("Toggle Expansion") {
isExpanded.toggle()
}
}
// .padding(10) // Adding a non-zero padding makes the glitch disappear
.frame(maxWidth: .infinity)
.geometryGroup()
.animation(.default, value: isExpanded)
}
}
#Preview {
ContentView().preferredColorScheme(.dark)
}
// MARK: - Mock Data
let loremIpsum = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt \
ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco \
laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla \
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt \
mollit anim id est laborum.
"""
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hi.
I know to know which window gets hardware keyboard events (such as shortcut key) currently on iPad.
Until iPadOS 15.0, UIApplication.shared.keyWindow, which was deprecated on iPadOS 13.0 and didBecomeKeyNotification/didResignKeyNotification.
But after iPadOS 15.0, a keyWindow is managed by UIScene, not by UIApplication.
Each scene of my app always has just one window.
For my purpose, checking deprecated UIApplication.shared.keyWindow is still effective but didBecomeKeyNotification and didResignKeyNotification don't work because they are fired when a change happens only inside the scene.
So my questions are,
What is the new alternative of UIApplication.shared.keyWindow?
I know a wrong hack like
UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first?.windows.filter { $0.isKeyWindow }.first
does not work since the order of connectedScenes is not related with getting hardware keyboard events.
What are the new alternatives of didBecomeKeyNotification/didResignKeyNotification which work on inter-scene?
The second question is more crucial.
Because about the first question, I can still use deprecated UIApplication.shared.keyWindow.
Thanks.
In iOS 18, I've observed unexpected behavior related to the UINavigationBar when transitioning between view controllers that have differing navigation bar visibility settings. Specifically, when returning from a modal presentation or a web view, the navigation bar reappears with an unexpected height (e.g., 103 points) and lacks content, displaying only an empty bar.
Start with a UIViewController (e.g., HomeViewController) where the navigation bar is hidden using:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
}
Present another UIViewController (e.g., a web view) modally.
Dismiss the presented view controller.
Observe that upon returning to HomeViewController, the navigation bar is visible with increased height and lacks expected content.
Expected Behavior:
The navigation bar should remain hidden upon returning to HomeViewController, maintaining the state it had prior to presenting the modal view controller.
Actual Behavior:
Upon dismissing the modal view controller, the navigation bar becomes visible with an unexpected height and lacks content, leading to a disrupted user interface.
Additional Observations:
This issue is specific to iOS 18; it does not occur in iOS 17 or earlier versions.
The problem seems to stem from setting the navigation bar to be visible in the viewWillDisappear method, as shown below:
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
Removing or modifying this line mitigates the issue, suggesting a change in the view controller lifecycle behavior in iOS 18.
Request for Clarification:
Is this change in behavior intentional in iOS 18, or is it a regression? Understanding whether this is a new standard or a bug will help in implementing appropriate solutions.
Workaround:
As a temporary measure, I've adjusted the navigation bar visibility settings to avoid changing its state in viewWillDisappear, instead managing it in viewWillAppear or viewDidAppear.
References:
Similar issues have been discussed in the Apple Developer Forums: iPad OS 18 UINavigationBar display incorrectly
Topic:
UI Frameworks
SubTopic:
UIKit
now i must use voip + livekit to developing, When incoming offline messages arrive at the device through VoIP, call ConversationManager The method of reporting NewIncomingConversation (uuid: update:) only first time can push new system UI,second or more time will crash, and acrsh stack appears to indicate that callkit has not been called
Topic:
UI Frameworks
SubTopic:
General
I’m working with AppIntents and AppEntity to integrate my app’s data model into Shortcuts and Siri. In the example below, I define a custom FoodEntity and use it as a @Parameter in an AppIntent. I’m providing dynamic options for this parameter via an optionsProvider.
In the Shortcuts app, everything works as expected: when the user runs the shortcut, they get a list of food options (from the dynamic provider) to select from.
However, in Siri, the experience is different. Instead of showing the list of options, Siri asks the user to say the name of the food, and then tries to match it using EntityStringQuery.
I originally assumed this might be a design decision to allow hands-free use with voice, but I found that if you use an AppEnum instead, Siri does present a tappable list of options. So now I’m wondering: why the difference?
Is there a way to get the @Parameter with AppEntity + optionsProvider to show a tappable list in Siri like it does in Shortcuts or with an AppEnum?
Any clarification on how EntityQuery.suggestedEntities() and DynamicOptionsProvider interact with Siri would be appreciated!
struct CaloriesShortcuts: AppShortcutsProvider {
static var appShortcuts: [AppShortcut] {
AppShortcut(
intent: AddCaloriesInteractive(),
phrases: [
"Add to \(.applicationName)"
],
shortTitle: "Calories",
systemImageName: "fork"
)
}
}
struct AddCaloriesInteractive: AppIntent {
static var title: LocalizedStringResource = "Add to calories log"
static var description = IntentDescription("Add Calories using Shortcuts.")
static var openAppWhenRun: Bool = false
static var parameterSummary: some ParameterSummary {
Summary("Calorie Entry SUMMARY")
}
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(stringLiteral:"Add to calorie log")
}
@Dependency
private var persistenceManager: PersistenceManager
@Parameter(title: LocalizedStringResource("Food"), optionsProvider: FoodEntityOptions())
var foodEntity: FoodEntity
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog {
return .result(dialog: .init("Added \(foodEntity.name) to calorie log"))
}
}
struct FoodEntity: AppEntity {
static var defaultQuery = FoodEntityQuery()
@Property var name: String
@Property var calories: Int
init(name: String, calories: Int) {
self.name = name
self.calories = calories
}
static var typeDisplayRepresentation: TypeDisplayRepresentation {
TypeDisplayRepresentation(name: "Calorie Entry")
}
static var typeDisplayName: LocalizedStringResource = "Calorie Entry"
var displayRepresentation: AppIntents.DisplayRepresentation {
DisplayRepresentation(title: .init(stringLiteral: name), subtitle: "\(calories)")
}
var id: String {
return name
}
}
struct FoodEntityQuery: EntityQuery {
func entities(for identifiers: [FoodEntity.ID]) async throws -> [FoodEntity] {
var result = [FoodEntity]()
for identifier in identifiers {
if let entity = FoodDatabase.allEntities().first(where: { $0.id == identifier }) {
result.append(entity)
}
}
return result
}
func suggestedEntities() async throws -> [FoodEntity] {
return FoodDatabase.allEntities()
}
}
extension FoodEntityQuery: EntityStringQuery {
func entities(matching string: String) async throws -> [FoodEntity] {
return FoodDatabase.allEntities().filter({$0.name.localizedCaseInsensitiveCompare(string) == .orderedSame})
}
}
struct FoodEntityOptions: DynamicOptionsProvider {
func results() async throws -> ItemCollection<FoodEntity> {
ItemCollection {
ItemSection("Section 1") {
for entry in FoodDatabase.allEntities() {
entry
}
}
}
}
}
struct FoodDatabase {
// Fake data
static func allEntities() -> [FoodEntity] {
[
FoodEntity(name: "Orange", calories: 2),
FoodEntity(name: "Banana", calories: 2)
]
}
}
Hello everyone,
I’m currently developing an iOS app and would like to leverage the AccessorySetupKit framework introduced in iOS 18 to implement pairing functionality with our company's custom hardware product. The specific requirements are as follows:
Our hardware supports both Bluetooth and Wi-Fi connections, and both are enabled.
When the hardware device is in proximity to an iPhone, I want the device to be automatically recognized, and a pairing screen similar to the one in AccessorySetupKit should appear.
Users should be able to perform the pairing process without needing to open our app, even if the app is not in the foreground. The system-level pairing screen should show the hardware information and allow the user to proceed with the pairing.
My questions are:
Does AccessorySetupKit allow the pairing screen to trigger when the app is running in the background, or must the app be in the foreground?
How should I configure AccessorySetupKit to automatically recognize and display my company’s hardware device information? Are there any specific configurations or code implementations needed?
Do I need to implement any specific Bluetooth/Wi-Fi advertising broadcasts to ensure the device is correctly detected by the iOS system when in proximity?
Are there any additional permissions or configurations required, especially for handling background tasks?
Thank you very much for your help, and I look forward to your advice and insights!
Topic:
UI Frameworks
SubTopic:
UIKit
https://github.com/apple/sample-food-truck
Hi! I'm seeing what looks like some weird navigation issue in the Food Truck app. It's from the Live Activity that should deep link to a specific point in the app. There seems be some state where the app is not linking to the correct component. Here are my repro steps on iPhone:
Start live activity from OrderDetailView.
Navigate to Sidebar component.
Tap the Live Activity.
App opens TruckView.
The App should be opening the OrderDetailView for the Order that was passed to the Live Activity. This seems to work when the app is not currently on Sidebar.
Any ideas? I'm testing this on iPhone OS 18.4.1. Is this an issue inside NavigationSplitView? Is this an issue with how Food Truck handles deeplinking?
When pushing a page in the navigation, changing the state of interactivePopGestureRecognizer causes the page to freeze.
Just like this:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
CGFloat red = (arc4random_uniform(256) / 255.0);
CGFloat green = (arc4random_uniform(256) / 255.0);
CGFloat blue = (arc4random_uniform(256) / 255.0);
CGFloat alpha = 1.0; //
self.view.backgroundColor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 100, 44);
btn.backgroundColor = [UIColor redColor];
btn.center = self.view.center;
[btn setTitle:@"push click" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
- (void)click:(id)sender {
[self.navigationController pushViewController:[ViewController new] animated:YES];
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}
@end
Let's say you have a protocol that can work with both classes and structs but you want to have a uniform UI to make edits.
What is the recommended way to have one view that will take both?
App
import SwiftUI
@main
struct ObservationTesterApp: App {
var body: some Scene {
WindowGroup {
ContentView(existence: Existence())
}
}
}
Types
import Foundation
protocol Dateable {
var timestamp:Date { get set }
}
struct Arrival:Dateable {
var timestamp:Date
}
@Observable
class Existence:Dateable {
var timestamp:Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
extension Existence {
convenience init() {
self.init(timestamp: Date())
}
}
ContentView, etc
//
// ContentView.swift
// ObservationTester
//
//
import SwiftUI
struct EditDateableView<TimedThing:Dateable>:View {
@Binding var timed:TimedThing
//note that this currently JUST a date picker
//but it's possible the protocol would have more
var body:some View {
DatePicker("Time To Change", selection: $timed.timestamp)
}
}
#Preview {
@Previewable @State var tt = Arrival(timestamp: Date())
EditDateableView<Arrival>(timed: $tt)
}
struct ContentView: View {
@State var arrival = Arrival(timestamp: Date())
@Bindable var existence:Existence
var body: some View {
//this work around also not allowed. "self is immutable"
// let existBinding = Binding<Existence>(get: { existence }, set: { existence = $0 })
VStack {
EditDateableView(timed: $arrival)
//a Binding cant take a Bindable
//EditDateableView<Existence>(timed: $existence)
}
.padding()
}
}
#Preview {
ContentView(existence: Existence())
}
As you can see in the screenshot, the verification popups that appear when making a StoreKit purchase cut off the buttons. When typing the code into the input field, the window will also flicker and stutter with random view refreshes. Is this something I can configure/change? It's not a very pleasant experience for making an in app purchase.
I'm trying to switch to UIKit's document lifecycle due to serious bugs with SwiftUI's version.
However I'm noticing the template project from Xcode isn't compatible with Swift 6 (I already migrated my app to Swift 6.). To reproduce:
File -> New -> Project
Select "Document App" under iOS
Set "Interface: UIKit"
In Build Settings, change Swift Language Version to Swift 6
Run app
Tap "Create Document"
Observe: crash in _dispatch_assert_queue_fail
Does anyone know of a work around other than downgrading to Swift 5?