gpt4 book ai didi

c# - 调用 iOS Alert 时出现 UI 一致性错误

转载 作者:行者123 更新时间:2023-11-29 12:00:39 25 4
gpt4 key购买 nike

我有一个 iOS Xamarin 项目,但出现以下错误:

    UIKit Consistency error: you are calling a UIKit method that 
can only be invoked from the UI thread.

此错误发生在以下代码中:

在我的欢迎 View 页面中,我有一个名为 SyncButton 的按钮,可以单击该按钮。单击该按钮应该使用 REST 与服务器同步数据。

在我的 WelcomeController 中我有:

....
SyncButton.TouchUpInside += async (object sender, EventArgs e) => {
SyncButton.Enabled = false;

await welcomeDelegate.syncButtonCore (cred, iOSErrorAlert);

SyncButton.Enabled = true;
};
....

public void iOSErrorAlert(string LoginErrorTitle, string LoginErrorMessage){
var Alert = UIAlertController.Create (LoginErrorTitle, LoginErrorMessage, UIAlertControllerStyle.Alert);
Alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Cancel, null));
PresentViewController (Alert, animated: true, completionHandler: null);

}

警报应该在确实存在超时或其他错误时发生。

SyncButtonCore() 包含在如下所示的委托(delegate)类中:

public async Task syncButtonCore(UserCredentials cred, RequestWithAlertDelegate.ErrorAlert NativeAlert){
await Task.Run (async ()=>{
RequestWithAlertDelegate requestWithAlert = new RequestWithAlertDelegate();
string URL = URLs.BASE_URL + URLs.CASELOAD + "/" + cred.PID;
await requestWithAlert.RequestWithRetry(URL, cred.UserID, cred.Password, NativeAlert, null, async delegate (string Response1){...}, 1);

我的 RequestWithAlert 类在哪里:

public async Task RequestWithRetry (string URL, string UserID, string Password, ErrorAlert NativeAlert, SyncAction Action, AsyncAction Action2, int times)
{
...make sure legit credentials...
if (LoginError) {
NativeAlert (LoginErrorTitle, LoginErrorMessage);
}

在最后一段代码中,我在 NativeAlert() 函数中遇到错误。这最终引发了我在

的代码开头提到的 UIKit 错误
var Alert = UIAlertController.Create (LoginErrorTitle, LoginErrorMessage, UIAlertControllerStyle.Alert);

我不确定我在这里做错了什么以及为什么我不允许创建此警报,因为我在我的 WelcomeController 中定义了它,这是我的 UIThread 应该正确的地方?

最佳答案

问题出在我的 iOSErrorAlert() 函数中。我需要用 InvokeOnMainThread() 包围它,因为 UI 操作应该在主线程中执行(我没有这样做,因为我将它传递给其他类/线程)。感谢@Paulw11 的评论。

必须替换这个:

public void iOSErrorAlert(string LoginErrorTitle, string LoginErrorMessage){
var Alert = UIAlertController.Create (LoginErrorTitle, LoginErrorMessage, UIAlertControllerStyle.Alert);
Alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Cancel, null));
PresentViewController (Alert, animated: true, completionHandler: null);
}

有了这个:

public void iOSErrorAlert(string LoginErrorTitle, string LoginErrorMessage){
InvokeOnMainThread (() => {
var Alert = UIAlertController.Create (LoginErrorTitle, LoginErrorMessage, UIAlertControllerStyle.Alert);
Alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Cancel, null));
PresentViewController (Alert, animated: true, completionHandler: null);
});
}

关于c# - 调用 iOS Alert 时出现 UI 一致性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37172290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com