Provide views, controls, and layout structures for declaring your app's user interface using SwiftUI.

Posts under SwiftUI tag

200 Posts

Post

Replies

Boosts

Views

Activity

backgroundPreferenceValue does not work after distributed through App Connect
Hi, I'm new to software development and facing a problem that don't know how to solve. I have a piece of code using .backgroundPreferenceValue and .anchorPreference modifiers to monitor a button's position while dragging. It works perfectly on preview, simulator, and my own device if I download it through a cable connected to my computer. However, today I distributed it to TestFlight and found out it broke. I repeated the process serval times but the result is still the same. Has anybody run into the same type of problem before? Desperately need help. Many many thanks!
2
0
358
Jan ’25
SwiftUI - Open a file via a fileURL
I am writing a SwiftUI-based app and have the following requirements: Use a file browser (such as UIDocumentPickerViewController) to find an arbitrary file (not one that the application knows how to open) which is external to the app bundle but local to the device the app is running on - either in local storage or on an iCloud drive. Save this location. At a later time, open this file. The file should open in an app that knows how to open it or in a browser. Do all of the above in a way that works with multiple devices (synced via CloudKit/SwiftData). For example, select a file on my iCloud drive on my Mac, then save it (using CloudKit/SwiftData) and open it on an iPad that has an app that can open it. I am addressing requirement #1 using UIDocumentPickerViewController wrapped with a UIViewControllerRepresentable. It returns a security-scoped URL. (Note: this worries me because of requirement #4). I use the Bookmark API to implement requirement #2. For requirement #3, I load the bookmark data, convert it back to a security-scoped URL and either Link("Open", destination: url) or @Environment(\.openURL) private var openURL if url.startAccessingSecurityScopedResource() { defer { url.stopAccessingSecurityScopedResource() } openURL(url) { accepted in // do something here } } Both of these implementations fail. The Link call responds with "invalid input parameters" (Error Domain=NSOSStatusErrorDomain, Code=-50), the openURL() call just returns false. So, my questions are: Since it appears the Link and openURL work for internet URLs, but not for security-scoped file URLs, how to I cause a document to be opened (using an application which knows how to open it or a browser). Since UIDocumentPickerViewController is returning a security-scoped URL, how can I make this work on a different device than the one on which the user selected the document? (Assuming, of course, that we are talking about a document that is on an iCloud drive that both devices have access to).
3
0
3.5k
Jan ’25
Help Needed: SwiftUI View with Camera Integration and Core ML Object Recognition
Hi everyone, I'm working on a SwiftUI app and need help building a view that integrates the device's camera and uses a pre-trained Core ML model for real-time object recognition. Here's what I want to achieve: Open the device's camera from a SwiftUI view. Capture frames from the camera feed and analyze them using a Create ML-trained Core ML model. If a specific figure/object is recognized, automatically close the camera view and navigate to another screen in my app. I'm looking for guidance on: Setting up live camera capture in SwiftUI. Using Core ML and Vision frameworks for real-time object recognition in this context. Managing navigation between views when the recognition condition is met. Any advice, code snippets, or examples would be greatly appreciated! Thanks in advance!
1
0
701
Jan ’25
Could someone test if Settings in iOS 18.2 are broken ?
Apparently, settings do not show anymore the apps settings in iOS 18.2. I tested on simulators (Xcode 16.2) both on iOS 18.1 and iOS 18.2 and got very different results: In iOS 18.1 simulator, I see the settings of a lot of apps. In iOS 18.2 simulator, not a single app setting. That is a really serious issue in simulator for development (I filed a bug report FB16175635), but would be really critical on device as it would make it impossible to adjust setting of many apps. Unless I missed something (meta setting ?) in iOS 18.2 ? I have not upgraded to 18.2 notably for this reason. So I would appreciate if someone who has upgraded could make the test and report ? select Settings on Home page scroll to Apps category tap here to access the list Does the list show anything ? Thanks for your help.
1
1
1.1k
Jan ’25
Writing to Printer with Core Bluetooth
I have a very cheap Bluetooth-connected printer. And I want to print out a word or two via Core Bluetooth. It's an iOS app with the SwiftUI framework. The following is what I have for an ObservableObject class. import Foundation import CoreBluetooth class BluetoothManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeripheralDelegate { @Published var connectedDevices: [CBPeripheral] = [] @Published var powerOn = false @Published var peripheralConnected = false private var centralManager: CBCentralManager! private var peripheralName = "LX-D02" private var connectedPeripheral: CBPeripheral? private var writeCharacteristic: CBCharacteristic? private let serviceUUID = CBUUID(string:"5833FF01-9B8B-5191-6142-22A4536EF123") private let characteristicUUID = CBUUID(string: "FFE1") override init() { super.init() self.centralManager = CBCentralManager(delegate: self, queue: nil) } func startScanning() { if centralManager.state == .poweredOn { centralManager.scanForPeripherals(withServices: nil, options: nil) } } func centralManagerDidUpdateState(_ central: CBCentralManager) { if central.state == .poweredOn { powerOn = true print("Bluetooth is powered on") } else { print("Bluetooth is not available") } } func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { if !connectedDevices.contains(peripheral) { if let localName = advertisementData["kCBAdvDataLocalName"] as? String { if localName == peripheralName { connectedDevices.append(peripheral) centralManager.connect(peripheral, options: nil) centralManager.stopScan() peripheralConnected = true print("Connected: \(peripheral.identifier.uuidString)") } } } } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { connectedPeripheral = peripheral peripheral.delegate = self let services = [serviceUUID] peripheral.discoverServices(services) //discoverServices(peripheral: peripheral) } func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: (any Error)?) { guard let error = error else { print("Failed connection unobserved") return } print("Error: \(error.localizedDescription)") } func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { if let error = error { print("Failing to discover servies: \(error.localizedDescription)") return } discoverCharacteristics(peripheral: peripheral) } /* Return all available services */ private func discoverServices(peripheral: CBPeripheral) { peripheral.discoverServices(nil) } private func discoverCharacteristics(peripheral: CBPeripheral) { guard let services = peripheral.services else { return } for service in services { peripheral.discoverCharacteristics(nil, for: service) } } func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { guard let characteristics = service.characteristics else { return } for characteristic in characteristics { let characteristicUUID = characteristic.uuid print("Discovered characteristic: \(characteristicUUID)") peripheral.setNotifyValue(true, for: characteristic) if characteristic.properties.contains(.writeWithoutResponse) { writeCharacteristic = characteristic print("You can write!!!") // Never read... } if characteristic.properties.contains(.write) { print("You can write?") writeCharacteristic = characteristic // Being read... } } func writeToPrinter() { guard let peripheral = connectedPeripheral else { print("Ughhh...") return } if let characteristic = writeCharacteristic { if let data = "Hello".data(using: .utf8, allowLossyConversion: true) { peripheral.writeValue(data, for: characteristic, type: .withoutResponse) peripheral.writeValue(data, for: characteristic, type: .withResponse) // -> Message sent successfully } } } func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { if let error = error { print("Writing error: \(error.localizedDescription)") return } print("Message sent successfully") } } My app has no trouble connecting to the bluetooth-connected printer. Initially, I called discoverServices(peripheral:) to get all services And I get a service identifier (5833FF01-9B8B-5191-6142-22A4536EF123) for my printer. peripheral(_:didDiscoverCharacteristicsFor:error:) doesn't return a thing for .writeWithoutResponse but does return a characteristic for .write. Eventually, if I call writeToPrinter(), peripheral.writeValue(data, for: characteristic, type: .withoutResponse) returns WARNING: Characteristic <CBCharacteristic: 0x3019040c0, UUID = 5833FF02-9B8B-5191-6142-22A4536EF123, properties = 0x8, value = (null), notifying = NO> does not specify the "Write Without Response" property - ignoring response-less write If I call peripheral.writeValue(data, for: characteristic, type: .withResponse) , there is no error. But I get no output from the printer. What am I doing wrong? Thanks.
1
0
438
Jan ’25
I want to know the update principle of the `RealityView`.
Here is the code snippets. struct RealityViewTestView: View { @State private var texts: [String] = [] var body: some View { RealityView { content, attachments in } update: { content, attachments in for text in texts { if let textEntity = attachments.entity(for: text) { textEntity.position.x = Float.random(in: -0.1...0.1) content.add(textEntity) } } } attachments: { ForEach(texts, id: \.self) { text in Attachment(id: text) { Text(text) .padding() .glassBackgroundEffect() } } } .toolbar { ToolbarItem { Button("Add") { texts.append(String(UUID().uuidString.prefix(6))) } } ToolbarItem { Button("Remove") { texts.remove(at: Int.random(in: 0..<texts.count)) } } } } } struct RealityViewTestView: View { @State private var texts: [String] = [] @State private var entities: [Entity] = [] var body: some View { RealityView { content, attachments in } update: { content, attachments in // for text in texts { // if let textEntity = attachments.entity(for: text) { // textEntity.position.x = Float.random(in: -0.1...0.1) // content.add(textEntity) // } // } for entity in entities { content.add(entity) } } attachments: { ForEach(texts, id: \.self) { text in Attachment(id: text) { Text(text) .padding() .glassBackgroundEffect() } } } .toolbar { ToolbarItem { Button("Add") { //texts.append(String(UUID().uuidString.prefix(6))) let m = ModelEntity(mesh: .generateSphere(radius: 0.1), materials: [SimpleMaterial(color: .white, isMetallic: false)]) m.position.x = Float.random(in: -0.2...0.2) entities.append(m) } } ToolbarItem { Button("Remove") { //texts.remove(at: Int.random(in: 0..<texts.count)) entities.removeLast() } } } } } About the first code snippet, when I remove an element from the texts, why content can automatically remove the corresponding entity? And about the second code snippet, content do not automatically remove the corresponding entity. I am very curious.
1
0
416
Jan ’25
searchable issue on iOS 18
Starting with iOS 18, the behavior of searchable and searchSuggestions differs from previous versions. In iOS 17.5, searchSuggestions remained visible even after selecting an item and navigating away. However, in iOS 18, searchSuggestions are dismissed after navigation. Is there a way to keep searchSuggestions visible after navigation, as in iOS 17.5? struct ContentView: View { @State private var query = "" var body: some View { NavigationStack { Color.red .searchable(text: $query) .searchSuggestions { NavigationLink("Element") { Color.blue } } } } } iOS 18.1 iOS 17.5
2
0
371
Jan ’25
LazyVGrid inside a List Crashes on iPhone 15 Pro Max (iOS 18.x) Simulator
We've seen an issue when using a LazyVGrid inside a List. The app crashes with: Thread 1: Fatal error: <UpdateCoalescingCollectionView 0x600000ca0d20> is stuck in a recursive layout loop When debugging the issue, we were able to narrow down the issue to a minimum reproducible example below: struct ContentView: View { let columns = [ GridItem(.adaptive(minimum: 43)) ] var body: some View { List { LazyVGrid(columns: columns) { ForEach(0..<15) { value in if value == 0 { Text("a") } else { Color.clear } } } } } } The issue can be reproduced on iPhone 15 Pro Max and iOS 18.x specifically. In a production app we have a similar layout, but instead of GridItem(.adaptive) we use GridItem(.flexible).
3
2
547
Jan ’25
My SwiftUI menu item renders differently in a MenuBarExtra / NSStatusBar
Hi, I'm working on an app that will mostly live in the menu bar. I'm trying to make a menu item that looks similar to the Tailscale app's menu: Note: I'm inspired by how Tailscale's menu is rendered: I have made a View that shows my avatar, name, and optionally the company I work for: import SwiftUI struct MenuWhoAmI: View { var username: String var binding: String? var body: some View { HStack { AsyncImage(url: URL(string: "https://avatars.githubusercontent.com/u/76716")!){ image in image.resizable().scaledToFit() } placeholder: { ProgressView() } .clipShape(Circle()) VStack(alignment: .leading) { Text(username) if let binding = binding { Text("\(binding)").foregroundStyle(.secondary) } } } } } #Preview { VStack(alignment: .leading) { MenuWhoAmI(username: "grahamc").padding() Divider() MenuWhoAmI(username: "grahamc", binding: "DeterminateSystems").padding() }.padding() } I tried using it in my menu bar: import SwiftUI @main struct DeterminateApp: App { var body: some Scene { MenuBarExtra("Determinate", image: "MenuIcon") { MenuWhoAmI(username: "grahamc") Button("Two") {} Button("Three") {} Divider() Button("Quit") { NSApplication.shared.terminate(nil) }.keyboardShortcut("q") }.menuBarExtraStyle(.menu) } } and it renders differently: After reading the forums and documentation, I understood the MenuBarExtra only renders certain elements. I then tried to use an NSStatusBar with an AppDelegate: import AppKit import SwiftUI @main struct DeterminateApp: App { @NSApplicationDelegateAdaptor private var appDelegate: AppDelegate var body: some Scene { Window("Authentication", id: "login") {} } } class AppDelegate: NSObject, NSApplicationDelegate, ObservableObject { private var statusItem: NSStatusItem! func applicationDidFinishLaunching(_ notification: Notification) { statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) if let button = statusItem.button { button.image = NSImage(named: NSImage.Name("MenuIcon")) } statusItem.menu = NSHostingMenu(rootView: Group { Button(action: { print("hi") }) { MenuWhoAmI(username: "grahamc") } }) } } and still, the avatar/name doesn't render like I'd expect, missing the circle clipping: ...and I'm a bit mystified. How can I make this menu render the way I'm trying for? Thank you!
1
0
482
Jan ’25
Registering a macOS app for dynamic text sizing in macOS 15
macOS 15 includes a neat section in System Preferences Settings to change the dynamic text size, as outlined see: https://support.apple.com/guide/mac-help/make-text-and-icons-bigger-mchld786f2cd/mac However, it's not immediately clear a) how to get one's app in this list, and b) if the usual methods from iOS to react to text size even work on macOS. Does anyone have any experience here? Or should I implement my own controls in my app's settings and call it a day? For context, my app is a macOS-native SwiftUI app.
1
0
564
Jan ’25
SwiftUI Menu with NavigationLinks inside overall NavigationStack
I've read all previous posts on this topic but none seem to address what I'm seeing for iOS 16 and using NavigationStack. I'm also using an overall @EnvironmentObject for navigation state. I have a split view app. In the detail section, I have a NavigationStack surrounding the detail view. Within the detail view (MyView), there is a base view with a "+" button in the toolbar to create a new entity. That opens NewEntityView where I show a grid of buttons for the user to select a type to create a new entity before moving to NewEntityView to fill in the details for the entity. The top row of the grid of buttons takes the user straight to the NewEntityView with a NavigationLink. These work fine. The next row of buttons present a menu of sub-types and then should take the user to the NewEntityView view. These buttons do not work. Code (simplified to not have clutter): SplitViewDetailView: struct SplitViewDetailView: View { @EnvironmentObject var navigationManager: NavigationStateManager @Binding var selectedCategory: Route? var body: some View { NavigationStack(path: $navigationManager.routes) { // other irrelevant stuff MyView() } .environmentObject(navigationManager) .navigationDestination(for: Route.self) { $0 } } } MyView: struct MyView: View { @EnvironmentObject var navigationManager: NavigationStateManager var body: some View { List { // other stuff } .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button(action: {}, label: { NavigationLink(value: Route.newTypeSelect) { Image(systemName: "plus") .frame(width: 44, height: 44) } } ) } } .navigationDestination(for: Route.self) { $0 } } SelectTypeView: struct SelectTypeView: View { var body: some View { ZStack { VStack { // Top row with no subtypes HStack { ForEach (topRows, id: \.self) { type in NavigationLink(value: Route.newEntityDetails(type.rawValue)) { <-- these work Text(type) } } } HStack { ForEach (middleRow, id: \.self) { type in Menu { ForEach (subtype[type], id: \.self) { sub in NavigationLink(value: Route.newEntityDetails(sub.rawValue)) { <-- these go nowhere Text(sub) } } } label: { Text(type) } } } } } } } NavigationStateManager: class NavigationStateManager: ObservableObject { @Published var routes = [Route]() // other stuff } And Route: enum Route: Identifiable { var id: UUID { UUID() } case newTypeSelect case newEntityDetails(String) } extension Route: View { var body: some View { switch self { case .newTypeSelect: SelectTypeView() case .newEntityDetails(let type): NewEntityView(selectedType: type) } } } The menus show up fine but tapping on an item does nothing. I've attempted to wrap the menu in its own NavigationStack but that is rejected stating it is already in one defined by a parent view. I've tried making the links Buttons with destinations and those are also rejected. What is the newest/best way to present a menu with NavigationLinks? One doesn't simply wrap the menu in a NavigationView if one is using a NavigationStack?
1
0
1.2k
Jan ’25
Broken focus on TabView with more than 7 tabs on tvos18
I am using the TabView control in SwiftUI on a tvOS 18 target with the style of sidebarAdaptable. When I have 7 or less tabs things operate correctly. When I add an 8th tab and you navigate to the contents of the tab the menu collapses as expected but you cannot navigate back to restore the menu. This code reproduces the issue: import SwiftUI struct ContentView: View { var body: some View { TabView { Tab("Tab1", systemImage: "person.circle") { Button("Button1") {} } Tab("Tab2", systemImage: "person.circle") { Button("Button2") {} } Tab("Tab3", systemImage: "person.circle") { Button("Button3") {} } Tab("Tab4", systemImage: "person.circle") { Button("Button4") {} } Tab("Tab5", systemImage: "person.circle") { Button("Button5") {} } Tab("Tab6", systemImage: "person.circle") { Button("Button6") {} } Tab("Tab7", systemImage: "person.circle") { Button("Button7") {} } Tab("Tab8", systemImage: "person.circle") { Button("Button8") {} } } .tabViewStyle(.sidebarAdaptable) } } If you eliminate Tab 8 the problem goes away. You can navigate back to the menu by moving to the left. Notably the Destination Video sample also reproduces this issue: https://developer.apple.com/documentation/visionos/destination-video To reproduce: Load the above code or Destination Video sample. Navigate right (click right on remote or swipe right). Menu dismisses and just shows the item you have selected in the upper left corner. Try to navigate left by clicking left on the remote or swiping left. It looks like the collapsed menu gets focus briefly, screen elements flash but the focus remains outside the menu. Has anyone else encountered this issue?
4
3
496
Jan ’25
Can’t focus the sidebar on tvOS when TabView contains TabSection elements
In a TabView with the .sidebarAdaptable style, including TabSection elements prevents the default back swipe on the remote from revealing the sidebar. Removing all TabSection elements and using only Tab elements makes it work as expected: import SwiftUI struct ContentView: View { var body: some View { TabView { Tab("Tab", systemImage: "square.fill") { Button(action: {}) { Text("Button") } } Tab("Tab", systemImage: "square.fill") { Button(action: {}) { Text("Button") } } Tab("Tab", systemImage: "square.fill") { Button(action: {}) { Text("Button") } } Tab("Tab", systemImage: "square.fill") { Button(action: {}) { Text("Button") } } Tab("Tab", systemImage: "square.fill") { Button(action: {}) { Text("Button") } } Tab("Tab", systemImage: "square.fill") { Button(action: {}) { Text("Button") } } Tab("Tab", systemImage: "square.fill") { Button(action: {}) { Text("Button") } } Tab("Tab", systemImage: "square.fill") { Button(action: {}) { Text("Button") } } Tab("Tab", systemImage: "square.fill") { Button(action: {}) { Text("Button") } } TabSection("Section") { Tab("Tab", systemImage: "square.fill") { Button(action: {}) { Text("Button") } } Tab("Tab", systemImage: "square.fill") { Button(action: {}) { Text("Button") } } } }.tabViewStyle(.sidebarAdaptable) } } Am I using it wrong, or is this a bug?
3
2
788
Jan ’25
.onMove does not work properly
Hello, I have a problem with the .onMove function. I believe I have set everything up properly. However, the moving does not seem to be working correctly. When I try to move the item, it is highlighted first, as it is supposed to be. Then, while I am moving it through the list, it disappears for some reason, and at the end of the move, it comes back to its initial place. (I use iOS 16.0 minimum, so I don't have to include the EditButton(). It works the same in the edit mode tho) import SwiftUI struct Animal: Identifiable { var id = UUID() var name: String } struct ListMove: View { @State var animals = [Animal(name: "Dog"), Animal(name: "Cat"), Animal(name: "Cow"), Animal(name: "Goat"), Animal(name: "Chicken")] var body: some View { List { ForEach(animals) { animal in Text(animal.name) } .onMove(perform: move) } } func move(from source: IndexSet, to destination: Int) { animals.move(fromOffsets: source, toOffset: destination) } } #Preview { ListMove() }
3
2
1.1k
Dec ’24
NSItemProvider make .jpg image to .jpeg
Hi, I'm not sure why but when my fileURL is .jpg file and I drop the file from my app to Finder folders it make the dropped file as .jpeg Is there a way to fix it? [.onDrag { if FileManager.default.fileExists(atPath: file.path) { // Provide the file as an item for dragging let fileURL = URL(fileURLWithPath: file.path) let itemProvider = NSItemProvider(contentsOf: fileURL) // Remove the file extension in the suggestedName let baseNameWithoutExtension = fileURL.deletingPathExtension().lastPathComponent itemProvider?.suggestedName = baseNameWithoutExtension return itemProvider ?? NSItemProvider() } else { // Handle the case where the file no longer exists print("File no longer exists at path: \(file.path)") return NSItemProvider() } })
0
0
345
Dec ’24
SwiftUI From/List Issue: All Buttons Trigger Simultaneously in List View
Hello everyone, I am a beginner in programming and recently encountered an interesting issue in SwiftUI. (I must admit that it might not be a bug and could simply be due to my lack of understanding.) I have extracted the relevant code that causes this behavior. Here's the code: struct BugView: View { var body: some View { List { VStack { Button("Bug") { print("1") } Button("Bug") { print("2") } Button("Bug") { print("3") } } } } } In this view, clicking any of the buttons results in all of them being triggered simultaneously. As a result, the console outputs: 1 2 3 I would appreciate it if someone could help me understand why this happens and how to fix it. Thanks in advance!
3
0
424
Dec ’24
Inconsistent DragGesture translation?
I feel like I must be missing something dumb, but I can't figure it out. I'm trying to create a modifier to make items resizable by dragging on the corner (I haven't actually implemented the corner part yet though so dragging anywhere on the object resizes it). However the rate that I'm dragging at is different from the rate that the object is resizing. It's also different for horizontal and vertical translation (the horizontal change is smaller than the rate that I'm dragging while the vertical change is larger). Any help would be greatly appreciated! Here's my code for the modifier: struct Resizable: ViewModifier { @State var size: CGSize = CGSize(width: 500, height: 500) @State var activeSize: CGSize = .zero func body(content: Content) -> some View { content .frame(width: abs(size.width + activeSize.width), height: abs(size.height + activeSize.height)) // offset is so the top right corner doesn't move .offset(x: -abs(size.width + activeSize.width) / 2, y: abs(size.height + activeSize.height) / 2) .gesture( DragGesture() .onChanged { gesture in activeSize.width = -gesture.translation.width activeSize.height = gesture.translation.height } .onEnded { _ in size.width += activeSize.width size.height += activeSize.height activeSize = .zero } ) } } extension View { func resizable(maxSize: CGSize = .zero) -> some View { modifier(Resizable()) } } And it is used like so: struct ContentView: View { var body: some View { Rectangle() .fill(Color.blue) .resizable() } }
1
0
410
Dec ’24
SwiftUI creating MapCameraPosition from CLLocationManager initialiser/self error when trying to tie them? (see code)
Trying to use new Swift @Observable to monitor GPS position within SwiftUI content view. But how do I tie the latest locations to the SwiftUI Map's mapCameraPosition? Well ideally the answer could cover: How to fix this error - So get map tracking along with the User Position, but also How to include facility to turn on/off the map moving to track the user position (which I'll need to do next). So could be tracking, then disable, move map around and have a look at things, then click button to start syncing the mapcameraposition to the GPS location again Refer to error I'm embedded in the code below. import SwiftUI import MapKit @Observable final class NewLocationManager : NSObject, CLLocationManagerDelegate { var location: CLLocation? = nil private let locationManager = CLLocationManager() func startCurrentLocationUpdates() async throws { if locationManager.authorizationStatus == .notDetermined { locationManager.requestWhenInUseAuthorization() } for try await locationUpdate in CLLocationUpdate.liveUpdates() { guard let location = locationUpdate.location else { return } self.location = location } } } struct ContentView: View { var newlocationManager = NewLocationManager() @State private var cameraPosition: MapCameraPosition = .region(MKCoordinateRegion( center: newlocationManager.location?.coordinate ?? <#default value#>, span: MKCoordinateSpan(latitudeDelta: 0.25, longitudeDelta: 0.25) )) // GET ERROR: Cannot use instance member 'newlocationManager' within property initializer; property initializers run before 'self' is available var body: some View { ZStack { Map(position: $cameraPosition) Text("New location manager: \(newlocationManager.location?.description ?? "NIL" )") // works } .task { try? await newlocationManager.startCurrentLocationUpdates() } } } #Preview { ContentView() }
2
0
1.5k
Dec ’24