I'm working on an iOS app using SwiftUI and CoreData and am running into a problem that I cannot seem to figure out.
To provide a little bit of information of what I am trying to do:
I have two CoreData entities that have a One-To-Many relationship:
Tarantula - A tarantula may molt many times (To Many) and when deleted, all of the molts shold also be removed (Cascade)
Molt - A molt belongs to a single Tarantula (To One) and when
deleted, should have the reference removed from the Tarantula (Nullify)
I then have a view that lists all of the molts for a given Tarantula that allows adding and deleting molts. It looks like this:
struct MoltListView: View {
		private static let DATE_FORMATTER: DateFormatter = {
						let d = DateFormatter()
						d.dateFormat = "MMM d, y"
						return d
				}()
		
		@Environment(\.managedObjectContext) private var viewContext
		
		@ObservedObject private var tarantula: Tarantula
		@FetchRequest private var molts: FetchedResults<Molt>
		@State private var userMessage: String = ""
		@State private var displayMessage: Bool = false
		
		init(tarantula: Tarantula) {
				self.tarantula = tarantula
				self._molts = FetchRequest(entity: Molt.entity(),
																	 sortDescriptors: [NSSortDescriptor(keyPath: \Molt.date, ascending: false)],
																	 predicate: NSPredicate(format: "tarantula = %@", tarantula))
		}
		
		var body: some View {
				List {
						Section(header: Text("Summary")) {
								Text("\(molts.count) Molt\(molts.count == 1 ? "" : "s")")
						}
						Section(header: Text("Molts")) {
								NavigationLink(destination: MoltView(tarantula: tarantula, molt: Molt.newModel())) {
										Text("Add Molt").foregroundColor(.blue)
								}
								ForEach(molts, id: \.self) { molt in
										NavigationLink(destination: MoltView(tarantula: tarantula, molt: molt)) {
												Text(MoltListView.DATE_FORMATTER.string(from: molt.modelDate))
										}
								}
								.onDelete(perform: deleteItems)
						}
				}.alert(isPresented: $displayMessage) {
						Alert(title: Text("Save Failure"), message: Text(userMessage), dismissButton: .default(Text("Ok")))
				}
		}
		
		private func deleteItems(offsets: IndexSet) {
				withAnimation {
						offsets.map { molts[$0] }.forEach(viewContext.delete)
						do {
								try viewContext.save()
						} catch {
								viewContext.rollback()
								userMessage = "\(error): \(error.localizedDescription)"
								displayMessage.toggle()
						}
				}
		}
}
The error I am experiencing comes from whenever I try to delete a molt from the list view. The app instantly crashes and the error is:
Simultaneous accesses to 0x7f92efc61cb8, but modification requires exclusive access
Find the complete error here:
error - https://developer.apple.com/forums/content/attachment/6d74dcde-d82b-4024-ade0-5936d8926488
I have tried removing the animation block and have played around with removing different UI components/restructuring.
The only way I have been able to prevent this error is to remove the delete rule on the Molt->Tarantula relationship from Nullify to No Action. However, this seems more like a hack to me instead of a fix.
Was hoping for some help on this issue.
SwiftUI
RSS for tagProvide views, controls, and layout structures for declaring your app's user interface using SwiftUI.
Posts under SwiftUI tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I am developing an app in swiftUI using Xcode 12.3, deployment target iOS 14.0. The launch screen is setup through info.plist by specifying 'background color' and 'image name'. The file used in 'image name' is from Assets catalog. (PNG format, size300 x 300 and corresponding @2x and @3x resolutions) What I have observed, when the app is installed for the first time the launch image is centered and have original resolutions but all subsequent launches show launch images stretched to cover full screen. Any ideas why this is happening and how to have more consistent behavior either way?
I have tried 'respect safe area' option but it does not make a difference.
Thank you.
I have recently started Beta Testing my SwiftUI App on my iPhone 6s, previously I was testing it on the iPhone 12 Simulator. While Testing on the Real Device I encountered issues like: CPU going past 98%
Really Laggy ScrollView
Tab Bar Freezes Randomly
Since My app is going to go in Production State in a few days, Since this is my first iOS App as well, I am not too sure if these issues are because of SwiftUI, my Phone or what, I have asked Apple Support but, haven't received a response so far.
My App Stats:
Lines of Code: ~1,500
CPU Usage on Simulator: Max. 10%
Bundle Size: 2MB
RAM Max. on Simulator: 32.3mb
Hi guys.
I have a question related to the next behavior.
I have ContentView with a list of views where the corresponding view models are passed. The user can click by some view. At the moment full-screen modal dialog will be shown according to the passed type. It's fine.
At some time my view models are being updated and the whole ContentView will be reloaded. The problem is: fullScreenCover is called and ChildEventView is recreated. How to prevent recreating ChildEventView?
struct ContentView: View {
		@ObservedObject private var eventListViewModel = EventListViewModel()
		@State private var fullScreenType: FullScreenType?
		/* some stuff */
		var body: some View {
				ScrollView {
						LazyVStack {
								ForEach(eventListViewModel.cardStates.indices, id: \.self) { index in
										let eventVM = eventListViewModel.eventVMs[index]
										EventCardView(eventViewModel: eventVM, eventId: $selectedEvent.eventId) {
												self.fullScreenType = .type1
										}
										/* some other views */
								}
						}
				}	
				.fullScreenCover(item: $fullScreenType, onDismiss: {
						self.fullScreenType = nil
				}, content: { fullScreenType in
						switch fullScreenType {
								case .type1:
								return ChildEventView(selectedEvent.eventId).eraseToAnyView()
								/* some other cases */
						}
				})
		}
}
How do I make a SwiftUI view fullscreen running Mac OS, Catalina or Big Sur?
I have been working with UIViewRepresentable a lot recently and noticed something that seems to be quite the flaw:
There doesn't seem to be a clean way of passing data back to your swiftUI views in a performant way.
Here is an example:
struct MapWrapper: UIViewRepresentable {
		@Binding var centerCoordinate: CLLocationCoordinate2D
		init(centerCoordinate: Binding<CLLocationCoordinate2D>) {
				self._centerCoordinate = centerCoordinate
		}
		func makeUIView(context: Context) -> MKMapView {
				var mapView = MKMapView()
				mapView.delegate = context.coordinator
				return mapView
		}
		
		func updateUIView(uiView: MKMapView, context: Context) {
				// Updating the maps center coordinate triggers mapViewDidChangeVisibleRegion, which thus causes updateUIView to trigger again.
				uiView.centerCoordinate = centerCoordinate
		}
		func makeCoordinator() -> Coordinator {
				return Coordinator(parent: self)
		}
		class Coordinator: MKMapViewDelegate {
				var parent: MapWrapper
				init(parent: MapWrapper) {
						self.parent = parent
				}
				func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
						// updating this variable causes a view reload, thus calling updateUIView, and eventually causing this delegate method to trigger again.
						parent.centerCoordinate = mapView.centerCoordinate
}
}
As you can see from the above code, dragging the map anywhere would cause a loop.
The only workaround I have found for this is to give your coordinator a "shouldUpdateState" Boolean variable. and set that prior to updating your bindings.
Has this ever been addressed by apple anywhere? Or are we just expected to only modify our view state from the outside of a UIViewRepresentable?
Hello, I connected Universal Links between the website and the application, everything was done according to the official documentation, and everything works fine, when the site is launched, safari offers to launch the application, there is also a banner above the launch page. In SwiftUI, I listen to the URL via .onOpenURL (perform :), everything works, but if the link is encoded in a QR code and scanned through the camera, a plate will appear prompting you to go to the application, and it goes, but only does not pass the URL to the .onOpenURL method (perform: ) . What could be the problem ?
Hi,
my app sees quite a lot of crashes (crash report below) and I have no clue how to debug the problem any further.
The problems seems only to occur on macOS 11. Is there anyone als having this kind of problems? Are there fixes/workarounds?
The source code of my app is open source - https://github.com/PDF-Archiver/PDF-Archiver if anyone would like to have a look into it.
OS Version: macOS 11.2.2 (20D80)
Report Version: 104
Exception Type: EXC_BAD_INSTRUCTION (SIGILL)
Exception Codes: ILL_NOOP at 0x00007fff2ca430f4
Crashed Thread: 0
Application Specific Information:
Fatal error SwiftUI
Thread 0 Crashed:
0 libswiftCore.dylib 0xfffe591310f4 _assertionFailure
1 SwiftUI 0xfffe8516c6fc ViewCache.commitPlacedChildren
2 SwiftUI 0xfffe850727f4 IncrementalChildPlacements.updateValue
3 SwiftUI 0xfffe8512890e Attribute.initT
4 AttributeGraph 0xfffe8625b17e AG::Graph::UpdateStack::update
5 AttributeGraph 0xfffe8625b607 AG::Graph::update_attribute
6 AttributeGraph 0xfffe862638f2 AG::Subgraph::update
7 SwiftUI 0xfffe85463679 GraphHost.runTransaction
8 SwiftUI 0xfffe85464bce GraphHost.runTransaction
9 SwiftUI 0xfffe85463ec8 GraphHost.flushTransactions
10 SwiftUI 0xfffe85464b6e GraphHost.asyncTransactionT
11 SwiftUI 0xfffe85464738 @callee_guaranteed
12 SwiftUI 0xfffe84d172b0 ViewGraphDelegate.updateGraphT
13 SwiftUI 0xfffe853201b9 ViewRendererHost.updateViewGraphT
14 SwiftUI 0xfffe8531e2a8 ViewRendererHost.updateViewGraphT
15 SwiftUI 0xfffe85329e98 NSHostingViewT
16 SwiftUI 0xfffe84d12f06 ViewGraphDelegate.updateGraphT
17 SwiftUI 0xfffe84d17258 NSHostingViewT
18 SwiftUI 0xfffe85464b49 GraphHost.init
19 SwiftUI 0xfffe84d18c9b @callee_guaranteed
20 SwiftUI 0xfffe8537a250 @callee_guaranteed
21 SwiftUI 0xfffe85377ee5 NSRunLoop.flushObservers
22 SwiftUI 0xfffe8537a198 NSRunLoop.addObserver
23 SwiftUI 0xfffe853755fd @callee_guaranteed
24 libswiftObjectiveC.dylib 0xfffe66ed2d9d autoreleasepoolT
25 SwiftUI 0xfffe8537a182 NSRunLoop.addObserver
26 SwiftUI 0xfffe8537a1ca NSRunLoop.addObserver
27 CoreFoundation 0xfffe40ab4dac __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__
28 CoreFoundation 0xfffe40ab4c3c __CFRunLoopDoObservers
29 CoreFoundation 0xfffe40ab3745 CFRunLoopRunSpecific
30 HIToolbox 0xfffe5101162f RunCurrentEventLoopInMode
31 HIToolbox 0xfffe5101142b ReceiveNextEventCommon
32 HIToolbox 0xfffe5101114e _BlockUntilNextEventMatchingListInModeWithFilter
33 AppKit 0xfffe45b349b0 _DPSNextEvent
34 AppKit 0xfffe45b33176 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:]
35 AppKit 0xfffe45b25689 -[NSApplication run]
36 AppKit 0xfffe45af996e NSApplicationMain
37 SwiftUI 0xfffe84ab59f3 runApp
38 SwiftUI 0xfffe8534c791 runAppT
39 SwiftUI 0xfffe84ecb09c App.main
40 PDFArchiver 0x2067699b0 [inlined] PDFArchiverApp.$main
41 PDFArchiver 0x2067699b0 main
42 libdyld.dylib 0xfffe40967620 start
Crash Report - https://developer.apple.com/forums/content/attachment/8bc85490-ee29-4233-91e2-63ff3cd0d3b8
Hi everyone,
I'm trying to follow the Landmarks project tutorial and got stuck in the second part, in the second section (Create the Row View), step 6 where it says "Modify the text view to use the landmark property’s name." This must be done in the LandmarkRow.swift file.
https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation
The tutorial shows that after doing this, the preview will display the name of the landmark (Turtle Rock) instead of the usual "Hello world" greeting. But my replacement is not happening. Moreover, from this point on, the preview stops working. There are no error messages in the code, except for the message that the preview could not be performed.
I checked and rewrote the code several times, replaced the data source files, but nothing helped.
At the same time, the preview works well in other view files.
I can't figure out what's wrong with my code? Any ideas as to what the reason will be is appreciated.
Below is the code of two files, the LandmarkRow.swift, where view does not work, the second is ModelData.swift and it is related to the previous one.
LandmarkRow.swift
import SwiftUI
struct LandmarkRow: View {
var landmark: Landmark
var body: some View {
HStack {
landmark.image
.resizable()
.frame(width: 50, height: 50)
Text(landmark.name)
Spacer()
}
}
}
struct LandmarkRow_Previews: PreviewProvider {
static var previews: some View {
LandmarkRow(landmark: landmarks[0])
}
}
ModelData.swift
import Foundation
var landmarks: [Landmark] = load("landmarkData.json")
func loadT: Decodable(_ filename: String) - T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
I tried animating the scrollTo() like so, as described in the docs. - https://developer.apple.com/documentation/swiftui/scrollviewreader
swift
withAnimation {
scrollProxy.scrollTo(index, anchor: .center)
}
the result is the same as if I do
swift
withAnimation(Animation.easeIn(duration: 20)) {
scrollProxy.scrollTo(progress.currentIndex, anchor: .center)
}
I tried this using the example from the ScrollViewReader docs.
With the result that up and down scrolling has exactly the same animation.
struct ScrollingView: View {
@Namespace var topID
@Namespace var bottomID
var body: some View {
ScrollViewReader { proxy in
ScrollView {
Button("Scroll to Bottom") {
withAnimation {
proxy.scrollTo(bottomID)
}
}
.id(topID)
VStack(spacing: 0) {
ForEach(0..100) { i in
color(fraction: Double(i) / 100)
.frame(height: 32)
}
}
Button("Top") {
withAnimation(Animation.linear(duration: 20)) {
proxy.scrollTo(topID)
}
}
.id(bottomID)
}
}
}
func color(fraction: Double) - Color {
Color(red: fraction, green: 1 - fraction, blue: 0.5)
}
}
struct ScrollingView_Previews: PreviewProvider {
static var previews: some View {
ScrollingView()
}
}
i get the expected expression error every time i restart Xcode i have tried numerous times to fix it here is the code
import SwiftUI
struct MainView: View {
var body: some View {
Color(.secondarySystemBackground)
HStack{
}
NavigationView{
Text("")
.navigationTitle("Home")
}
navigationBarItems(trailing:
Button(action: {
print("Hello")
}) {
Image(systemName: "square.and.pencil")
.resizable()
.frame(width: 50, height: 50)
) - Error Here
}
}
}
struct MainView_Previews: PreviewProvider {
static var previews: some View {
MainView()
}
}
Hello,
in my Mac Catalyst app, I have detail view with sections modeled as DisclosureGroups. The label view has a button, that shall trigger a file import view when pushed. The label view is defined as follows:
swift
HStack {
Text(LocalizedStringKey("Documents")).font(.title)
Spacer()
Button {
showFileImporter = false
// fix broken picker sheet
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
showFileImporter = true
}
} label: {
Image(systemName: "doc.badge.plus")
.padding(.horizontal, 10)
}
.disabled(!expanded)
.fileImporter(
isPresented: $showFileImporter,
allowedContentTypes: [.data],
allowsMultipleSelection: false) { result in
// add fileUrl.startAccessingSecurityScopedResource() before accessing file
NSLog("\(result)")
}
}
Unfortunately the file import view is not showing, when the button is pushed, although the state changes to true.
Does anybody have any hints?
BTW the repo is available at https://github.com/thbonk/repti/tree/ui-refactoring
The view in question is https://github.com/thbonk/repti/blob/ui-refactoring/Repti/Source/UI/Views/IndividualDetails/DocumentsSubview.swift
Thanks & Best regards
Thomas
I have an iOS app by using a swift package to hold most of the logic. However, the previews of SwiftUI views often fail with following error:
HumanReadableSwiftError
BuildError: failedToGenerateThunkInfo(Error Domain=com.apple.xcbuild Code=19 "could not generate preview info: noTargetBuildGraph" UserInfo={NSLocalizedDescription=could not generate preview info: noTargetBuildGraph})
To reproduce this, please clone https://github.com/pointfreeco/isowords and check for preview of ChangelogView.
I'm trying to store image data locally and the name of the image is retrieved from an API. In the situation where an image does not exist locally, I want to put a placeholder. Right now it just puts a white background.
Whenever I retrieve from the API I get a purple exclamation which is a warning but not an exception. How can I intercept this warning and make it show a placeholder instead?
One problem is that Image is not an optional. It just blithely accepts whatever is fed into it which is annoying. Is there a way to query the asset catalog if it contains something?
I have been playing around with the new AsyncImage Api in SwiftUI
I am using the initialiser that passes in a closure with the AsyncImagePhase, to view why an image may not load, when I looked at the error that is passed in if the phase is failure, the localised description of the error is "Cancelled" but this is happening before the view is being displayed.
I am loading these images in a list, I imagine I am probably doing something which is causing the system to decide to cancel the loading, but I cannot see what.
Are there any tips to investigate this further?
Hello
Is there way to keep calling a function (efficiently) while the view is on screen, without using a timer, in SwiftUI?
My goal is to create a chat view in SwiftUI. This requires creating a ScrollView with content of varying heights .
After extensive debugging, I've determined that if you have views within a LazyVStack inside of a ScrollView that do not have a fixed height, it will stutter when you scroll to the top of the view.
––––
PROJECT: Download this project and try for yourself
struct ContentView: View {
@State var items: [String] = MockData.randomMessages(count: 100)
var body: some View {
VStack {
Button("Shuffle items") {
items = MockData.randomMessages(count: 100)
}
ScrollView {
LazyVStack(spacing: 10) {
ForEach(Array(items.enumerated()), id: \.offset) { index, item in
Text(item)
.background(colors.randomElement()!)
}
}
}
}
}
}
My conclusion right now is that LazyVStack only works with child views that have fixed height. This issue alone prevents SwiftUI from being production ready.
Has anyone else tackled this?
How does one declare a TableColumn with a nullable field?
I have a Book model with several nullable fields:
struct Book: Codable, Equatable, Identifiable {
// ...
let productURL: String?
// ...
}
This is how I'm trying define the corresponding TableColumn:
TableColumn("Product URL", value: \.productURL) { book in
Text(String(book.productURL ?? ""))
}
Though this results in several errors:
Referencing initializer 'init(_:value:comparator:content:)' on 'TableColumn' requires that 'Book' inherit from 'NSObject'
Referencing initializer 'init(_:value:comparator:content:)' on 'TableColumn' requires that 'Book' inherit from 'NSObject'
Referencing initializer 'init(_:value:comparator:content:)' on 'TableColumn' requires the types 'KeyPathComparator' and 'SortDescriptor' be equivalent
Referencing initializer 'init(_:value:comparator:content:)' on 'TableColumn' requires the types 'KeyPathComparator' and 'SortDescriptor' be equivalent
Other, non-nullable columns work just fine. For example:
TableColumn("ID", value: \.id) { book in
Text(String(book.id))
}
TableColumn("Slug", value: \.slug)
TableColumn("Category", value: \.category)
TableColumn("Title", value: \.title)
// ...
How does one add Codable conformance to a class that needs to be isolated to the MainActor?
For example, the following code gives compiler errors:
@MainActor final class MyClass: Codable {
var value: Int
enum CodingKeys: String, CodingKey {
case value
}
init(from decoder: Decoder) throws { // <-- Compiler error: Initializer 'init(from:)' isolated to global actor 'MainActor' can not satisfy corresponding requirement from protocol 'Decodable'
let data = try decoder.container(keyedBy: CodingKeys.self)
self.value = try data.decode(Int.self, forKey: .value)
}
func encode(to encoder: Encoder) throws { // <-- Compiler error: Instance method 'encode(to:)' isolated to global actor 'MainActor' can not satisfy corresponding requirement from protocol 'Encodable'
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(value, forKey: .value)
}
}
I'm definitely struggling to get my head around actors and @MainActor at the moment!
Hi,
I'm trying to create a ViewController that extends UIHostingController and host an AttachmentView there. Also, I would like to pass an environment object to the AttachmentView, but I get a compile error because the type of rootView does not match what I specify in UIHostingController.
How can I get this code to compile?
Thanks!