supergeorg / Grocy-SwiftUI

A client for Grocy for macOS and iOS, written with SwiftUI
GNU General Public License v3.0
177 stars 17 forks source link

Unknown error when navigating #167

Open FelixSFD opened 1 year ago

FelixSFD commented 1 year ago

In many cases (like 70-90%), where I navigate inside the app, I get this error-message:

image

When I tap "try again", the text vanished, but I still can't navigate.

image

According to the logs, the data requests fail with errorcode -999 (cancelled).

Video: https://github.com/supergeorg/Grocy-SwiftUI/assets/2721240/c71345e0-6b00-4c0e-9e9d-6f0f7bc8bff9

supergeorg commented 1 year ago

This happens when you navigate too fast 🙈 I will try to find the bug, for now navigate more slowly 😅

supergeorg commented 1 year ago

This seems to be the problem: If you have started a task using SwiftUI’s task() modifier, that task will automatically be canceled when the view disappears. Source: HackingWithSwift By switching fast, the fetch task gets cancelled. This needs some bigger changes (if it isn't too much work for such a small problem), so I will only release the bugfix for now.

FelixSFD commented 1 year ago

Thanks, that fix made the "Try Again" button work. 😊

I tried to debug the issue this morning, too, and I might have found a solution. However, this required some bigger changes in the GrocyAPI.callAPI(), so this will need extensive testing. I'm not an expert and new to this project, so I might have broken something else.

My approach

First, I changed the HTTP call from .data() to .dataTask() with a completion handler. I did this, because I couldn't find out, which exact line was throwing the exception, when the request was cancelled. Because I didn't want to change the rest of the class, I wrapped this new call inside withCheckedThrowingContinuation() to turn this into an async call. This didn't fix the issue completely, because there was a new warning in the log:

SWIFT TASK CONTINUATION MISUSE [...] leaked its continuation!

This error told me, what happened to the running tasks when navigating quickly: Something is wrong with the memory management of this class. So I switched the property grocyVM in the views from @SteteObject to @ObservedObject, which is recommended for properties that are not created inside the view, but injected instead: https://www.avanderlee.com/swiftui/stateobject-observedobject-differences/#should-i-use-stateobject-for-all-views-using-the-same-instance


I'll push my code in a new branch later, so you can have a look at my potential solution.