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
}
}];
}
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
There appears to be a visual bug when using .searchable in a child view that’s pushed via NavigationLink inside a NavigationStack. Specifically, the search bar appears briefly in the wrong position (or animates in an unexpected way) during the transition to the child view.
This issue does not occur when using NavigationView instead of NavigationStack.
Steps to Reproduce:
Create a TabView with a single tab containing a NavigationStack.
Push from a ContentView to a DetailsView using NavigationLink.
Add a .searchable modifier to both the ContentView and DetailsView.
Run the app and tap a row to navigate to the details view.
Expected Behavior
The search bar in the DetailsView should appear smoothly and in the correct position as the view transitions in, just like it does under NavigationView.
Actual Behavior
When the DetailsView appears, the search bar briefly animates or appears in the wrong location before settling into place. This results in a jarring or buggy visual experience.
Feedback: FB17031212
Here is a reddit thread discussing the issue as well https://www.reddit.com/r/SwiftUI/comments/137epji/navigation_stack_with_search_bar_has_a_bug_and_a/
I hope that an Apple engineer can get this fixed soon. It's frustrating to have new APIs come out with the old deprecated yet there are still obvious bugs two years later.
import SwiftUI
public enum Tab {
case main
}
struct AppTabNavigation: View {
@State private var tabSelection = Tab.main
var body: some View {
TabView(selection: $tabSelection) {
NavigationStack {
ContentView()
}
.tag(Tab.main)
.tabItem {
Label("Main", systemImage: "star")
}
}
}
}
struct ContentView: View {
@State private var searchText = ""
var body: some View {
List(0..<100) { i in
NavigationLink("Select \(i)", value: i)
}
.navigationTitle("Main")
.searchable(text: $searchText)
.navigationDestination(for: Int.self) { i in
DetailsView(i: i)
}
}
}
struct DetailsView: View {
@State private var searchText = ""
let i: Int
// MARK: - Body
var body: some View {
List {
ForEach(0..<10, id: \.self) { i in
Text("Hello \(i)")
}
}
.navigationTitle(i.formatted())
.searchable(text: $searchText)
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hello everyone,
The setup:
I have an iPadOS app.
The app does not require full screen (Requires full screen option is disabled).
The problem:
The app starts looking unpolished when the canvas becomes too small.
What I tried:
I am trying to limit the canvas size for our app when run in Stage Manager.
How:
I saw that UIWindowScene has sizeRestrictions. This property is not always set as per documentation:
https://developer.apple.com/documentation/uikit/uiwindowscene/sizerestrictions
From my experiments, it only works when it's run on MacOS (in compatibility mode in our case).
Console logs:
Stage Manager - Requires full screen - OFF
willConnectToSession - sizeRestrictions: nil
sceneDidBecomeActive - sizeRestrictions: nil
Stage Manager - Requires full screen - ON
willConnectToSession - sizeRestrictions: nil
sceneDidBecomeActive - sizeRestrictions: nil
Stage Manager - Requires full screen - OFF - RUN on MacOS
willConnectToSession - sizeRestrictions: Available
sceneDidBecomeActive - sizeRestrictions: Available
Question:
Is there a way to enforce this minimum canvas size?
Topic:
UI Frameworks
SubTopic:
UIKit
Hello, I have encountered a question that I hope to receive an answer to. Currently, I am working on a music project for Mac Catalyst and need to enable music files such as FLAC to be opened by right clicking to view my Mac Catalyst app. But currently, I have encountered a problem where I can see my app option in the right-click open mode after debugging the newly created macOS project using the following configuration. But when I created an iOS project and converted it to a Mac Catalyst app, and then modified the info.plist with the same configuration, I couldn't see my app in the open mode after debugging. May I ask how to solve this problem? Do I need to configure any permissions or features in the Mac Catalyst project? I have been searching for a long time but have not found a solution regarding it. Please resolve it, thank you.
Here is the configuration of my macOS project:
CFBundleDocumentTypes
CFBundleTypeExtensions
flac
CFBundleTypeIconSystemGenerated
1
CFBundleTypeName
FLAC Audio File
CFBundleTypeRole
Viewer
LSHandlerRank
Default
Note: Sandbox permissions have been enabled for both the macOS project and the iOS to Mac Catalyst project. The Mac Catalyst project also has additional permissions for com. apple. security. files. user taught. read write
My assumption has always been that [NSApp runModalForWindow:] runs a modal window in NSModalPanelRunLoopMode.
However, while -[NSApplication _doModalLoop:peek:] seems to use NSModalPanelRunLoopMode when pulling out the next event to process via nextEventMatchingMask:untilDate:inMode:dequeue:, the current runloop doesn't seem to be running in that mode, so during -[NSApplication(NSEventRouting) sendEvent:] of the modal-specific event, NSRunLoop.currentRunLoop.currentMode returns kCFRunLoopDefaultMode.
From what I can tell, this means that any event processing code that e.g. uses [NSTimer addTimer:forMode:] based on the current mode will register a timer that will not fire until the modal session ends.
Is this a bug? Or if not, is the correct way to run a modal session something like this?
[NSRunLoop.currentRunLoop performInModes:@[NSModalPanelRunLoopMode] block:^{
[NSApp runModalForWindow:window];
}];
[NSRunLoop.currentRunLoop limitDateForMode:NSModalPanelRunLoopMode];
Alternatively, if the mode of the runloop should stay the same, I've seen suggestions to run modal sessions like this:
NSModalSession session = [NSApp beginModalSessionForWindow:theWindow];
for (;;) {
if ([NSApp runModalSession:session] != NSModalResponseContinue)
break;
[NSRunLoop.currentRunLoop limitDateForMode:NSModalPanelRunLoopMode];
}
[NSApp endModalSession:session];
Which would work around the fact that the timer/callbacks were scheduled in the "wrong" mode. But running NSModalPanelRunLoopMode during a modal session seems a bit scary. Won't that potentially break the modality?
I’m having a weird UIKit problem. I have a bunch of views in a UIScrollView and I add a UIContextMenuInteraction to all of them when the view is first loaded. Because they're in a scroll view, only some of the views are initially visible.
The interaction works great for any of the views that are initially on-screen, but if I scroll to reveal new subviews, the context menu interaction has no effect for those.
I used Xcode's View Debugger to confirm that my interaction is still saved in the view's interactions property, even for views that were initially off-screen and were then scrolled in.
What could be happening here?
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?
Hello,
I was wondering if someone could clear-up my thinking here.
e.g. consider the code below...
It has a rootView with a navlink to a childView which in turn has navlinks to GrandchildViews.
The root view uses basic navLInks NavigationLink{View} label: {View}
The child view uses type-based navLinks navigationLink(value:) {View} and .navigationDestination(for:) {View}
I would expect the basic navlinks to work in the root view and the type-based ones to work in the child view. However it appears that both are active when one taps on a link in the child view.
e.g. User actions:
Start -> RootView is only view on the stack -> (tap on ‘Child View’) -> ChildView is top of the stack -> tap on ‘Alice’ -> a second ChildView is top of the stack with a GrandchildView underneath….
Why does this happen, why are the basic links also applied to the childView's links?
Thanks.
struct Thing: Identifiable, Hashable {
let id = UUID()
let name: String
}
struct RootView: View {
var body: some View {
NavigationStack {
List {
NavigationLink {
ChildView()
} label: {
Label("Child View", systemImage: "figure.and.child.holdinghands")
}
NavigationLink {
Text("Hello")
} label: {
Label("Another navLink item in the list", systemImage: "circle")
}
}
.padding()
}
}
}
struct ChildView: View {
private var things = [
Thing(name: "Alice"),
Thing(name: "Bob"),
Thing(name: "Charlie"),
]
var body: some View {
Text("This is the child view")
List {
ForEach(things) { thing in
NavigationLink(value: thing) {
Text(thing.name)
}
}
}
.navigationTitle("Child View")
.navigationDestination(for: Thing.self) { thing in
GrandchildView(thing: thing)
}
}
}
struct GrandchildView: View {
let thing: Thing
var body: some View {
Text("This is the GrandchildView: \(thing.name)")
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Description
When using UIDocumentPickerViewController with allowsMultipleSelection = false, I expect that selecting a file will dismiss only the document picker.
However, if a user quickly taps the same file multiple times, the picker dismisses both itself and the presenting view controller (i.e., it pops two levels from the view controller stack), which leads to unintended behavior and breaks presentation flow.
Expected Behavior
Only UIDocumentPickerViewController should be dismissed when a file is selected—even if the user taps quickly or multiple times on the same file.
Actual Behavior
When tapping the same file multiple times quickly, the picker dismisses not only itself but also the parent view controller it was presented from.
Steps to Reproduce
Create a simple view controller and present another one modally over it.
From that presented view controller, present a UIDocumentPickerViewController with allowsMultipleSelection = false.
Tap quickly on the same file in the picker 2 times.
Result: Both the document picker and the presenting view controller are dismissed.
Reproducible Code Snippet
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .green
addLabel("Parent View Controller")
DispatchQueue.main.async { [unowned self] in
let child = UIViewController()
child.view.backgroundColor = .yellow
present(child, animated: true)
child.addLabel("Child View Controller")
let vc = UIDocumentPickerViewController(
forOpeningContentTypes: [.pdf, .jpeg, .png],
asCopy: true
)
vc.allowsMultipleSelection = false
child.present(vc, animated: true)
}
}
}
extension UIViewController {
func addLabel(_ text: String) {
let label = UILabel(frame: CGRect(x: 0, y: 50, width: view.bounds.width, height: 30))
label.text = text
view.addSubview(label)
}
}
Environment
Device: iPhone 15 Pro and others
iOS version: 18.2 (reproduces on multiple iOS versions)
Occurs with: .pdf, .jpeg, .png file types
Mode: Both simulator and real device
Notes
Happens consistently with fast multiple taps on the same file.
This breaks expected view controller stack behavior.
Hi,
Is there any way of changing the contentInset (UIKit variant) of a List in SwiftUI?
I do not see any APIs for doing so, the closest I gotten is to use safeAreaInset . While visually that works the UX is broken as you can no longer "scroll" from the gap made by the .safeAreaInset(edge:alignment:spacing:content:)
I have subbmited a feedback suggestion: FB16866956
I have the MainView as the active view if the user is logged in(authenticated). the memory allocations when we run profile is pretty good. We have graphql fetching, we have token handling eg: This is All heap:
1 All Heap & Anonymous VM 13,90 MiB 65408 308557 99,10 MiB 373965 Ratio: %0.14, %0.86
After what i have checked this is pretty good for initialise and using multiple repositories eg. But when we change tabs:
1 All Heap & Anonymous VM 24,60 MiB 124651 543832 156,17 MiB 668483 Ratio: %0.07, %0.40
And that is not pretty good. So i guess we need to "kill" it or something. How? I have tried some techniques in a forum this was a recommended way:
public struct LazyView<Content: View>: View {
private let build: () -> Content
@State private var isVisible = false
public init(_ build: @escaping () -> Content) {
self.build = build
}
public var body: some View {
build()
Group {
if isVisible {
build()
} else {
Color.clear
}
}
.onAppear { isVisible = true }
.onDisappear { isVisible = false }
}
}
But this did not help at all. So under here is the one i use now. So pleace guide me for making this work.
import DIKit
import CoreKit
import PresentationKit
import DomainKit
public struct MainView: View {
@Injected((any MainViewModelProtocol).self) private var viewModel
private var selectedTabBinding: Binding<MainTab> {
Binding(
get: { viewModel.selectedTab },
set: { viewModel.selectTab($0) }
)
}
public init() {
// No additional setup needed
}
public var body: some View {
NavigationStack(path: Binding(
get: { viewModel.navigationPath },
set: { _ in }
)) {
TabView(selection: selectedTabBinding) {
LazyView {
FeedTabView()
}
.tabItem {
Label("Feed", systemImage: "house")
}
.tag(MainTab.feed)
LazyView {
ChatTabView()
}
.tabItem {
Label("Chat", systemImage: "message")
}
.tag(MainTab.chat)
LazyView {
JobsTabView()
}
.tabItem {
Label("Jobs", systemImage: "briefcase")
}
.tag(MainTab.jobs)
LazyView {
ProfileTabView()
}
.tabItem {
Label("Profile", systemImage: "person")
}
.tag(MainTab.profile)
}
.accentColor(.primary)
.navigationDestination(for: MainNavigationDestination.self) { destination in
switch destination {
case .profile(let userId):
Text("Profile for \(userId)")
case .settings:
Text("Settings")
case .jobDetails(let id):
Text("Job details for \(id)")
case .chatThread(let id):
Text("Chat thread \(id)")
}
}
}
}
}
import SwiftUI
public struct LazyView<Content: View>: View {
private let build: () -> Content
public init(_ build: @escaping () -> Content) {
self.build = build
}
public var body: some View {
build()
}
}
Hi everyone! I'm thrilled to share that I'm conducting a field research as part of my final university project, focused on iOS architecture.
The goal is to dive deeper into the best practices, challenges, and trends in the iOS development world. To make this research truly impactful, I need your help!
If you're an iOS developer, I’d love it if you could take a few minutes to answer a short survey. Your insights and experiences will be invaluable for my research, and I greatly appreciate your
support!
Here is the link:
https://docs.google.com/forms/d/e/1FAIpQLSdf9cacfA7my1hnlazyl7uJraa2oTsQ7dJBWvFtZ_4vbYenRA/viewform?usp=send_form
Thank you so much in advance for helping me out—feel free to share this post with others who might also be interested. Let’s build something amazing together! 💡✨
Hi,
I’m practicing with NavigationSplitView for macOS and customizing the sidebar. I’ve managed to adjust most parts, but I couldn’t remove the sidebar’s divider. It seems like it’s not possible in modern SwiftUI. My AppKit knowledge is also not very strong.
How can I remove the sidebar divider?
I want to use a plain background. I also solved it by creating my own sidebar, but I wanted to try it using NavigationSplitView.
I have a controller that displays a pdf using UIDocumentInteractionController as the presented view.
When users open it up, it shows fine.
User gets the app backgrounded and session timed out.
After timed out, when the app is brought to foreground, I bring our loginVC by removing the old VC used to show the UIDocumentInteractionController.
All the crashes are happening at this point.
I am not able to reproduce it, but our alert systems show we have crashes happening.
The code that shows the pdf is straight forward
documentViewController = UIDocumentInteractionController()
documentViewController?.delegate = self
documentViewController?.url = url
documentViewController?.presentPreview(animated: true)
and we reset it to nil in delegate documentInteractionControllerDidEndPreview
Based on the crash trace, it seems like the crash happens when our login VC replaces it and only when pdf was displayed. The reason of stressing ONLY because when we have other viewcontroller present and they are removed in a similar way, we do not see any issue.
So we always replace first and then add a new one
childViewController.willMove(toParent: nil)
childViewController.viewIfLoaded?.removeFromSuperview()
childViewController.removeFromParent()
addChild(childViewController)
view.addSubview(childViewController.view)
childViewController.view.frame = view.bounds
childViewController.didMove(toParent: self)
Raised a ticket with Apple, but I haven't heard back, and it's been a month. Posting here in case anyone experiences the same and has any solutions. I saw some related posts, and solution was to remove the pdf the moment the app goes to the background, but I am trying to find some alternate solution if possible.
Topic:
UI Frameworks
SubTopic:
UIKit
I'm implementing a Map with user location customization in SwiftUI using iOS 17+ MapKit APIs. When using the selection parameter with Map, the default blue dot user location becomes tappable but shows an empty annotation view. However, using UserAnnotation makes the location marker non-interactive.
My code structure:
import SwiftUI
import MapKit
struct UserAnnotationSample: View {
@State private var position: MapCameraPosition = .userLocation(fallback: .automatic)
@State private var selectedItem: MapSelection<MKMapItem>?
var body: some View {
Map(position: $position, selection: $selectedItem) {
// UserAnnotation()
}
.mapControls {
MapUserLocationButton()
}
}
}
Key questions:
How can I replace the empty annotation view with a custom avatar when tapping the user location?
Is there a way to make UserAnnotation interactive with selection?
Should I use tag modifier for custom annotations? What's the proper way to associate selections?
I'm trying to make the side bar menu on my tvOS app have the same behavior of Apple's tvOS App. I would like to have the side menu collapsed at the cold start of the app. I'm trying to achieve this by using the defaultFocus view modifier, which should make the button inside the TabView focused at the start of the app. But no matter what I do, the side bar always steels the focus from the inside button.
struct ContentView: View {
enum Tabs {
case viewA
case viewB
}
enum ScreenElements {
case button
case tab
}
@FocusState private var focusedElement: ScreenElements?
@State private var selectedTab: Tabs? = nil
var body: some View {
Group {
TabView(selection: $selectedTab) {
Tab("View A", image: "square", value: .viewA) {
Button("View A Button", action: {})
.frame(maxWidth: .infinity, alignment: .center)
.focused($focusedElement, equals: .button)
}
}
.tabViewStyle(.sidebarAdaptable)
.focused($focusedElement, equals: .tab)
}
.defaultFocus($focusedElement, .button, priority: .userInitiated)
}
}
Is there a way to start the side bar menu collapsed at the start up of the app?
I want to truncate text from head with max 2 lines.
I try the following code
import SwiftUI
struct ContentView: View {
@State var content: String = "Hello world! wef wefwwfe wfewe weweffwefwwfwe wfwe"
var body: some View {
VStack {
Text(content)
.lineLimit(nil)
.truncationMode(.head)
.frame(height: 50)
Button {
content += content
} label: {
Text("Double")
}
.buttonStyle(.borderedProminent)
}
.frame(width: 200, height: 1000)
.padding()
}
}
#Preview {
ContentView()
}
It show result like this, this is not what I want.
Where from and how does an NSRulerView get its magnification from? I am not using the automatic magnification by NSScrollView but using my own mechanism. How do I relay the zoom factor to NSRulerView?
Hey Everyone,
I can't see to ActiveLabel as it says there is no active module. Please help me.
Thanks,
Ben
import UIKit
import ActiveLabel
protocol TweetCellDelegate: AnyObject {
func handleProfileImageTapped(_ cell: TweetCell)
func handleReplyTapped(_ cell: TweetCell)
func handleLikeTapped(_ cell: TweetCell)
}
class TweetCell: UICollectionViewCell {
Hi guys, I’m making a simple note taking app and I want to support markdown functionality. I have tried to find libraries and many other GitHub repos but some of them are slow and some of them are very hard to implement and not very customizable.
In WWDC 22 apple also made a markdown to html document app and I also looked at that code and it was awesome. It was fast and reliable (Apple btw).
But the only problem I am facing is that the markdown text is on the left side and the output format is on the right in the form of html. I don’t want that I want both in the same line. In bear notes and things 3 you can write in markdown and you can see that it is converting in the same line. I have also attached example videos. So, I have markdown parser by apple but the only thing in the way is that it is converting it into a html document. Please help me with this. Also please look into the things 3 video they have also completely customized the text attributes selection menu. By default with UITextView we can only enable text attributes and it shows like this.
By clicking more we get the complete formatting menu but not the slider menu which is more convenient. Please also help me this. I don’t know if I can provide apple file but it is from wwdc 22 supporting desktop class interaction