skip to Main Content

I’m using SwiftUI’s drag & drop modifiers. Since, iOS 15 gives an option to customise the onDrag modifier with a preview I’m using it as shown below.

Issue: I’ve a if #available(iOS 15.0, *) guard to choose the view for different iOS versions. But, somehow my app on iOS 14.x crashes due to an EXC_BAD_ACCESS (code=1, address=0x0) error since it tries to find the new API but it is not present in iOS 14.

@ViewBuilder
private func getRoutineCard(routine: RoutineInfo) -> some View {
    if #available(iOS 15.0, *) {
        newRoutineCard(routine: routine)
    } else {
        oldRoutineCard(routine: routine)
    }
}

@available(iOS 15.0, *)
@ViewBuilder
private func newRoutineCard(routine: RoutineInfo) -> some View {
    RoutineCard(routine: routine)
    // This modifier is what crashes the app on iOS 14.x
    // onDrag with a drag preview view not available in iOS 14.x
        .onDrag({
            dragReorder(draggedRoutine: routine)
        }, preview: {
            RoutineCardDragPreview(routine: routine)
        })
        .onDrop(of: [.text], delegate: ReorderDropDelegate(isDragging: $isDragging, draggedItem: $draggedItem, item: routine, haptics: haptics, onMove: updateOrder(routine:order:)))
}

@ViewBuilder
private func oldRoutineCard(routine: RoutineInfo) -> some View {
    RoutineCard(routine: routine)
        .onDrag { dragReorder(draggedRoutine: routine) }
        .onDrop(of: [.text], delegate: ReorderDropDelegate(isDragging: $isDragging, draggedItem: $draggedItem, item: routine, haptics: haptics, onMove: updateOrder(routine:order:)))
}

What I’m looking for: A workaround to choose between the two views based on the iOS version without causing a crash.

2

Answers


  1. To anyone stumbling upon this:

    When using if #available(iOS 14.0, OSX 11.0, *) inside a ViewBuilder, the application crashes when running on the fallback side.

    This happens with Xcode versions 13.1 and above. (Currently Xcode 13.2.1)
    Tested out with Xcode 13.0 build and crash is gone. We think this is because of compiler optimisation bug in Xcode. For development builds we do not have these crashes.

    More here: https://swiftui-lab.com/bug-os-check/
    and same answer:
    Swiftui app crashes with different SearchBar (ViewModifier) on iOS 14 / 15

    Login or Signup to reply.
  2. It’s due to the code which is written in ViewBuilder. That needs to be transferred to View Modifier

    Got solution https://stackoverflow.com/a/71908419/9970928

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search