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.

All subtopics

Post

Replies

Boosts

Views

Activity

No ObservableObject of Type "" found.
Im building an recipe app for the social media of my mother. i already have the functionality for the users, when a user gets created an empty array gets initiated at the database named favoriteRecipes, which stores the id of his favorite recipes to show in a view. This is my AuthViewModel which is relevant for the user stuff: import Firebase import FirebaseAuth import FirebaseFirestore protocol AuthenticationFormProtocol { var formIsValid: Bool { get } } @MainActor class AuthViewModel : ObservableObject { @Published var userSession: FirebaseAuth.User? @Published var currentUser: User? @Published var currentUserId: String? init() { self.userSession = Auth.auth().currentUser Task { await fetchUser() } } func signIn(withEmail email: String, password: String) async throws { do { let result = try await Auth.auth().signIn(withEmail: email, password: password) self.userSession = result.user await fetchUser() // fetch user sonst profileview blank } catch { print("DEBUG: Failed to log in with error \(error.localizedDescription)") } } func createUser(withEmail email: String, password: String, fullName: String) async throws { do { let result = try await Auth.auth().createUser(withEmail: email, password: password) self.userSession = result.user let user = User(id: result.user.uid, fullName: fullName, email: email) let encodedUser = try Firestore.Encoder().encode(user) try await Firestore.firestore().collection("users").document(result.user.uid).setData(encodedUser) await fetchUser() } catch { print("Debug: Failed to create user with error \(error.localizedDescription)") } } func signOut() { do { try Auth.auth().signOut() // sign out user on backend self.userSession = nil // wipe out user session and take back to login screen self.currentUser = nil // wipe out current user data model } catch { print("DEBUG: Failed to sign out with error \(error.localizedDescription)") } } func deleteAcocount() { let user = Auth.auth().currentUser user?.delete { error in if let error = error { print("DEBUG: Error deleting user: \(error.localizedDescription)") } else { self.userSession = nil self.currentUser = nil } } } func fetchUser() async { guard let uid = Auth.auth().currentUser?.uid else { return } currentUserId = uid let userRef = Firestore.firestore().collection("users").document(uid) do { let snapshot = try await userRef.getDocument() if snapshot.exists { self.currentUser = try? snapshot.data(as: User.self) print("DEBUG: current user is \(String(describing: self.currentUser))") } else { // Benutzer existiert nicht mehr in Firebase, daher setzen wir die userSession auf nil self.userSession = nil self.currentUser = nil } } catch { print("DEBUG: Fehler beim Laden des Benutzers: \(error.localizedDescription)") } } } This is the code to fetch the favorite recipes, i use the id of the user to access the collection and get the favoriteRecipes out of the array: import SwiftUI @MainActor class FavoriteRecipeViewModel: ObservableObject { @Published var favoriteRecipes: [Recipe] = [] @EnvironmentObject var viewModel: AuthViewModel private var db = Firestore.firestore() init() { Task { await fetchFavoriteRecipes() } } func fetchFavoriteRecipes() async{ let userRef = db.collection("users").document(viewModel.userSession?.uid ?? "") do { let snapshot = try await userRef.collection("favoriteRecipes").getDocuments() let favoriteIDs = snapshot.documents.map { $0.documentID } let favoriteRecipes = try await fetchRecipes(recipeIDs: favoriteIDs) } catch { print("DEBUG: Failed to load favorite recipes for user: \(error.localizedDescription)") } } func fetchRecipes(recipeIDs: [String]) async throws -> [Recipe] { var recipes: [Recipe] = [] for id in recipeIDs { let snapshot = try await db.collection("recipes").document(id).getDocument() if let recipe = try? snapshot.data(as: Recipe.self) { recipes.append(recipe) } } return recipes } } Now the Problem occurs at the build of the project, i get the error SwiftUICore/EnvironmentObject.swift:92: Fatal error: No ObservableObject of type AuthViewModel found. A View.environmentObject(_:) for AuthViewModel may be missing as an ancestor of this view. I already passed the ViewModel instances as EnvironmentObject in the App Struct. import SwiftUI import FirebaseCore class AppDelegate: NSObject, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { FirebaseApp.configure() return true } } @main struct NimetAndSonApp: App { @StateObject var viewModel = AuthViewModel() @StateObject var recipeViewModel = RecipeViewModel() @StateObject var favoriteRecipeViewModel = FavoriteRecipeViewModel() @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate var body: some Scene { WindowGroup { ContentView() .environmentObject(viewModel) .environmentObject(recipeViewModel) .environmentObject(favoriteRecipeViewModel) } } }
1
0
179
2w
can't install cocoaPods
need to use CocoaPods, Ruby, and Xcode to set up a development environment. trying to install CocoaPods and running into compatibility issues with Ruby versions (>= 2.7.0) and can't use rbenv.
1
0
138
2w
NSExtensionPointIdentifier key "com.apple.quicklook.preview" - which iOS versions are supported?
I am creating an iOS app to install on legacy iPads running iOS 9 and up, using XCode 13.4.1 which is the latest version that will support iOS below 11. The app is working fine but I just added a QuickLook Preview extension, and on iOS 10.3.1 it will not install due to the following error: This app contains an app extension that specifies an extension point identifier that is not supported on this version of iOS for the value of the NSExtensionPointIdentifier key in its Info.plist. Domain: com.apple.dt.MobileDeviceErrorDomain Code: -402653007 The NSExtensionPointIdentifier key in Info.plist is set by XCode automatically to "com.apple.quicklook.preview". I want to set the iOS Deployment Target to the lowest iOS version that will support this configuration. The documentation does not provide any guide as to which specific NSExtensionPointIdentifier keys are compatible with which iOS version. It just says 8+ for the whole list. Trial-and-error is limited by availability of legacy Simulators. If anyone can point to documentation that indicates which iOS is supported by which NSExtensionPointIdentifier key com.apple.quicklook.preview, I would be very grateful. Thanks (I understand about lack of App Store support etc, this is an app for my use on old iPads)
0
0
112
2w
SwiftData error "Thread 1: Fatal error: Composite Coder only supports Keyed Container"
I'm using SwiftData to store data in my app and I recently had to store both image data and colors. I have therefore added two variables to my model, one of type Data? and the other of type Color.Resolved? If both are set to nil then I can call context.save() without any error but when providing a value of type Color.Resolved, the following error message occurs: Thread 1: Fatal error: Composite Coder only supports Keyed Container. Any guidance on how to solve this and what needs to be done to store image data and colors with SwiftData?
1
0
135
2w
question about error
I am trying to work on a new app but everytime I try to run it and test it I get this error error reading dependency file '/Users/jacobwright/Library/Developer/Xcode/DerivedData/LevelingUp:_Life-baixnmqgtntqiacdkadvwrgeanox/Build/Intermediates.noindex/LevelingUp: Life.build/Debug-iphonesimulator/LevelingUp: Life iOS.build/Objects-normal/arm64/LevelingUp: Life iOS-master-emit-module.d': unexpected character in prerequisites and I do not know what to do. I even tryed makeing a new project and running it with out doing anything and I get the same thing I have tried Deleting Xcode and Reinstalling, and updating my computer and Xcode. I am not sure what else to try and I was wondering if anyone else is getting this and how do i fix it?
1
0
105
2w
Hide TabItems?
Is there really no way to hide a TabItem using the built-in TabView? I have 6 pages, but the 6th one I want hidden from the bottom tab bar, because I have a button that programmatically navigates to it on the navigation bar. I did not want to have to code a custom tab bar due to losing some useful features like pop to root in Navigation Stack.
0
0
119
2w
iOS18: UITabBarController.selectedViewController with UINavigationController
In a UITabBarController, its controllers are set to be UINavigationControllers. When programmatically setting the selectedViewController to a desired controller which is not currently displayed, the selected icon is correct however the actual view controller is still the previously selected. Pseudo code: tabController.controllers = [viewcontroller1, viewcontroller2, viewcontroller3].map{ UINavigationController(rootViewController: $0) } .... // let's say at some point tab bar is set to e.g. showing index 1 tabController.selectedController = tabController.controllers[0] // after this the icon of the 1st tab is correctly displayed, but the controller is still the one at index 1 I have noticed that if the controllers are simple UIViewController (not UINavigationController) upon setting the selectedViewController the TabController sets both icon and content correctly. But this is not the wanted setup and different UINavigationControllers are needed. Is this a new bug in iOS18? Any idea how to fix this (mis)behaviour?
1
0
220
2w
Main Thread blocked by synchronous property query (AVPlayer)
I want to play remote videos using an AVPlayer in my SwiftUI App. However, I can't fix the error: "Main thread blocked by synchronous property query on not-yet-loaded property (PreferredTransform) for HTTP(S) asset. This could have been a problem if this asset were being read from a slow network." My code looks like this atm: struct CustomVideoPlayer: UIViewControllerRepresentable { let myUrl: URL func makeCoordinator() -> Coordinator { return Coordinator(self) } func makeUIViewController(context: Context) -> AVPlayerViewController { let playerItem = AVPlayerItem(url: myUrl) let player = AVQueuePlayer(playerItem: playerItem) let playerViewController = AVPlayerViewController() playerViewController.player = player context.coordinator.setPlayerLooper(player: player, templateItem: playerItem) playerViewController.delegate = context.coordinator playerViewController.beginAppearanceTransition(true, animated: false) return playerViewController } func updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) { } static func dismantleUIViewController(_ uiViewController: AVPlayerViewController, coordinator: ()) { uiViewController.beginAppearanceTransition(false, animated: false) } class Coordinator: NSObject, AVPlayerViewControllerDelegate { var parent: CustomVideoPlayer var player: AVPlayer? = nil var playerLooper: AVPlayerLooper? = nil init(_ parent: CustomVideoPlayer) { self.parent = parent super.init() } func setPlayerLooper(player: AVQueuePlayer, templateItem: AVPlayerItem) { self.player = player playerLooper = AVPlayerLooper(player: player, templateItem: templateItem) } } } I already tried creating the AVPlayerItem/AVAsset on a background thread and I also tried loading the properties asynchronously before setting the player in makeUIViewController: let player = AVQueuePlayer(playerItem: nil) ... Task { let asset = AVAsset(url: myUrl) let _ = try await asset.load(.preferredTransform) let item = AVPlayerItem(asset: asset) player.replaceCurrentItem(with: item) } Nothing seems to fix the issue (btw: the main thread is actually blocked, there is a noticable animation hitch). Any help is much appreciated.
0
3
178
2w
Visual artifacts in LazyVStack
Some strange visual artifacts appeared in my app after updating Xcode to 16.0. The old version of the app was built with Xcode 15.x and working fine without any visual artifacts, but for the latest release I've used Xcode 16.0 and some strange visual artifacts appeared in LazyVStack on iOS 18.x. https://www.veed.io/view/828ed62c-a8ee-4102-846c-55b28a7f4b74?panel=share Anyone can help me with a fix or workaround ?
2
0
109
2w
Sheet presentationDetents breaks after rapid open/dismiss cycles
Basic Information Please provide a descriptive title for your feedback: Sheet presentationDetents breaks after rapid open/dismiss cycles Which platform is most relevant for your report? iOS Description Steps to Reproduce: Create a sheet with presentationDetents([.medium]) Rapidly perform these actions multiple times (usually 3-4 times): a. Open the sheet b. Immediately scroll down to dismiss Open the sheet again Observe that the sheet now appears at .large size, ignoring the .medium detent Expected Result: Sheet should consistently maintain .medium size regardless of how quickly it is opened and dismissed. Actual Result: After rapid open/dismiss cycles, the sheet ignores .medium detent and appears at .large size. Reproduction Rate: Occurs consistently after 3-4 rapid open/dismiss cycles More likely to occur with faster open/dismiss actions Configuration: iOS 18 Xcode 16.0 (16A242d) SwiftUI Device: iPhone 14
3
2
222
2w
Re-Visiting NSViewController.loadView's behaviour in 2024 and under macOS 15...
This is a post down memory lane for you AppKit developers and Apple engineers... TL;DR: When did the default implementation of NSViewController.loadView start making an NSView when there's no matching nib file? (I'm sure that used to return nil at some point way back when...) If you override NSViewController.loadView and call [super loadView] to have that default NSView created, is it safe to then call self.view within loadView? I'm refactoring some old Objective-C code that makes extensive use of NSViewController without any use of nibs. It overrides loadView, instantiates all properties that are views, then assigns a view to the view controller's view property. This seems inline with the documentation and related commentary in the header. I also (vaguely) recall this being a necessary pattern when not using nibs: @interface MyViewController: NSViewController // No nibs // No nibName @end @implementation MyViewController - (void)loadView { NSView *hostView = [[NSView alloc] initWithFrame:NSZeroRect]; self.button = [NSButton alloc...]; self.slider = [NSSlider alloc...]; [hostView addSubview:self.button]; [hostView addSubview:self.slider]; self.view = hostView; } @end While refactoring, I was surprised to find that if you don't override loadView and do all of the setup in viewDidLoad instead, then self.view on a view controller is non-nil, even though there was no nib file that could have provided the view. Clearly NSViewController has realized that: There's no nib file that matches nibName. loadView is not overridden. Created an empty NSView and assigned it to self.view anyways. Has this always been the behaviour or did it change at some point? I could have sworn that if there as no matching nib file and you didn't override loadView, then self.view would be nil. I realize some of this behaviour changed in 10.10, as noted in the header, but there's no mention of a default NSView being created. Because there are some warnings in the header and documentation around being careful when overriding methods related to view loading, I'm curious if the following pattern is considered "safe" in macOS 15: - (void)loadView { // Have NSViewController create a default view. [super loadView]; self.button = [NSButton...]; self.slider = [NSSlider...]; // Is it safe to call self.view within this method? [self.view addSubview:self.button]; [self.view addSubview:self.slider]; } Finally, if I can rely on NSViewController always creating an NSView for me, even when a nib is not present, then is there any recommendation on whether one should continue using loadView or instead move code the above into viewDidLoad? - (void)viewDidLoad { self.button = [NSButton...]; self.slider = [NSSlider...]; // Since self.view always seems to be non-nil, then what // does loadView offer over just using viewDidLoad? [self.view addSubview:self.button]; [self.view addSubview:self.slider]; } This application will have macOS 15 as a minimum requirement.
0
0
145
2w
MapSelection of MapFeatures and MKMapItems
I have a Map within a SwiftUI app that has the selection parameter set to an optional MapSelection. I need to be able to select MapFeatures which works as expected as well as MKMapItems which are added to the map. The MKMapItems are not selectable. Is it possible to make it such that the Map allows the user to select MKMapItems as well as MapFeatures?
1
0
116
2w
App that runs fine under Xcode 15 does not work on Xcode 16.
When I upgraded to Sequoia 15.1, an app that worked fine under OS 14 stopped working. Out of 4 views on the main screen, only 1 is visible. Yet, if I click where another view should be, I get the expected action so the views are there, just not visible. Only I can't see where I am clicking! I had to upgrade to Xcode 16 to recompile the app and run it in Debug mode. When I do, I get the following: NSBundle file:///System/Library/PrivateFrameworks/MetalTools.framework/ principal class is nil because all fallbacks have failed. Can't find or decode disabled use cases. applicationSupportsSecureRestorableState FWIW - the only view that actually shows up is the last subview added to the main view.
2
1
231
2w
MapFeature icon and color
I don't believe it's possible today to access the icon and tint color of a MapFeature although this would be incredibly helpful in the app that I'm building presently as I'm storing places in SwiftData and would like to use the same icon and tint color when listing places in the app. It would be awesome if this were possible in the next version of iOS, iPadOS visionOS etc., if not presently possible.
1
0
102
2w
Is it possible to generate nice PDF with gradient from SwiftUI view ?
I try to generate PDF from view. View is nice, there is a lot of transparency and many gradients (circular and linear). But if I use ImageRenderer in in a way that documentation suggest all transparency and gradients disappear. Is this bug or some feature? Is it way to generate vector graphic from view with transparency and gradients? PDF allows those features, so why not?
2
0
191
2w
SwiftUI FormView not updating after value creation/updating in a SubView
I'm developing a SwiftUI, CoreData / CloudKit App with Xcode 16.2 & Sequoia 15.2. The main CoreData entity has 20 NSManaged vars and 5 derived vars, the latter being computed from the managed vars and dependent computed vars - this somewhat akin to a spreadsheet. The data entry/updating Form is complex for each managed var because the user needs to be able to enter data in either Imperial or Metric units, and then switch (by Button) between units for viewing equivalents. This has to happen on an individual managed var basis, because some source data are in Imperial and others Metric. Consequently, I use a generalised SubView on the Form for processing the managed var (passed as a parameter with its identity) and then updating the CoreData Entity (about 100 lines of code in total): i.e. there are 20 uses of the generalised SubView within the Main Form. However, none of the SubViews triggers an update of the managed var in the Form, nor computations of the derived vars. On initial load of the app, the CoreData entity is retrieved and the computations happen correctly: thereafter not. No technique for refreshing either View works: e.g. trigger based on NSManagedObjectContextDidSave; nor does reloading the CoreData entity after Context Save (CoreData doesn't recognise changes at the attribute level anyway). If the SubView is removed and replaced with code within the Form View itself, then it works. However, this will require about 40 @State vars, 20 onCommits, etc - so it's not something I'm keen to do. Below is a much-simplified example of the problem. Form{ Section(header: Text("Test Record")){ Text(testRec.dateString ?? "n/a") TextField("Notes",text:$text) .onSubmit{ testRec.notes = text dataStore.contextSave() } //DoubleNumberEntry(testRec: testRec) - doesn't work TextField("Double",value:$numDbl,format: .number) // This works .onSubmit{ testRec.dblNum = numDbl dataStore.contextSave() } TextField("Integer",value: $numInt,format: .number) .onSubmit{ testRec.intNum = Int16(numInt) dataStore.contextSave() } Text(String(format:"%.2f",testRec.computation)) Section(header: Text("Computations")) { Text(String(format:"%.2f",testRec.computation)) Text(String(format:"%.2f",testRec.anotherComputation)) } } } A much simplified version of my NSManaged var entry/updating. struct DoubleNumberEntry: View { let dataStore = MainController.shared.dataStore var testRec : TestRec @State private var numDbl: Double init(testRec: TestRec) { self.testRec = testRec self.numDbl = testRec.dblNum } var body: some View { TextField("Double",value:$numDbl,format: .number) .onSubmit{ testRec.dblNum = numDbl dataStore.contextSave() } } } I'd appreciate any offered solution or advice. Regards, Michaela
1
0
184
2w
How To Create Dual Screen of AR using RealityView and SwiftUI iOS 18
I have this code to make ARVR Stereo View To Be Used in VR Box Or Google Cardboard, it uses iOS 18 New RealityView but it is not Act as an AR but rather Static VR on a Camera background so as I move the iPhone the cube move with it and that's not suppose to happen if its Anchored in a plane or to world coordinate. import SwiftUI import RealityKit struct ContentView : View { let anchor1 = AnchorEntity(.camera) let anchor2 = AnchorEntity(.camera) var body: some View { HStack (spacing: 0){ MainView(anchor: anchor1) MainView(anchor: anchor2) } .background(.black) } } struct MainView : View { @State var anchor = AnchorEntity() var body: some View { RealityView { content in content.camera = .spatialTracking let item = ModelEntity(mesh: .generateBox(size: 0.25), materials: [SimpleMaterial()]) anchor.addChild(item) content.add(anchor) anchor.position.z = -1.0 anchor.orientation = .init(angle: .pi/4, axis:[0,1,1]) } } } the thing is if I remove .camera like this let anchor1 = AnchorEntity() let anchor2 = AnchorEntity() It would work as AR Anchored to world coordinates but on the other hand is does not work but on the left view only not both views Meanwhile this was so easy before RealityView and SwiftUI by cloning the view like in ARSCNView Example : import UIKit import ARKit class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate { //create Any Two ARSCNView's in Story board // and link each to the next (dont mind dimensions) @IBOutlet var sceneView: ARSCNView! @IBOutlet var sceneView2: ARSCNView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. sceneView.delegate = self sceneView.session.delegate = self // Create SceneKit box let box = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.01) let item = SCNNode(geometry: box) item.geometry?.materials.first?.diffuse.contents = UIColor.green item.position = SCNVector3(0.0, 0.0, -1.0) item.orientation = SCNVector4(0, 1, 1, .pi/4.0) // retrieve the ship node sceneView.scene.rootNode.addChildNode(item) } override func viewDidLayoutSubviews() // To Do Add the 4 Buttons { // Stop Screen Dimming or Closing While The App Is Running UIApplication.shared.isIdleTimerDisabled = true let screen: CGRect = UIScreen.main.bounds let topPadding: CGFloat = self.view.safeAreaInsets.top let bottomPadding: CGFloat = self.view.safeAreaInsets.bottom let leftPadding: CGFloat = self.view.safeAreaInsets.left let rightPadding: CGFloat = self.view.safeAreaInsets.right let safeArea: CGRect = CGRect(x: leftPadding, y: topPadding, width: screen.size.width - leftPadding - rightPadding, height: screen.size.height - topPadding - bottomPadding) DispatchQueue.main.async { if self.sceneView != nil { self.sceneView.frame = CGRect(x: safeArea.size.width * 0 + safeArea.origin.x, y: safeArea.size.height * 0 + safeArea.origin.y, width: safeArea.size.width * 0.5, height: safeArea.size.height * 1) } if self.sceneView2 != nil { self.sceneView2.frame = CGRect(x: safeArea.size.width * 0.5 + safeArea.origin.x, y: safeArea.size.height * 0 + safeArea.origin.y, width: safeArea.size.width * 0.5, height: safeArea.size.height * 1) } } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let configuration = ARWorldTrackingConfiguration() sceneView.session.run(configuration) sceneView2.scene = sceneView.scene sceneView2.session = sceneView.session } } And here is the video for it
1
0
165
2w