如何修复#Xamarin.Forms中有关locationManagerDidChangeAuthorization和authorizationStatus的警告?

nhaq1z21  于 2023-06-20  发布在  其他
关注(0)|答案(1)|浏览(242)

首先,我做了一些研究,但只为Swift找到了一个原生的iOS答案。
完整的警告说:

This method can cause UI unresponsiveness if invoked on the main thread. Instead, consider waiting for the `-locationManagerDidChangeAuthorization:` callback and checking `authorizationStatus` first.

我读到过这可能是因为我使用的是异步,离开调用;以及.我已经阅读了有关的iOS版本也:StackOverFlow/73805219如何在Xamarin表单中修复此问题?
我必须说我正在使用#Xamarin.Forms.Essentials中的Geolocalization来获取我通过#MessaginCenter发送的异步函数中的当前经度和纬度。

async Task StoringNoteAsync()
        {
            Location location = await _geolocation.GetCurrentLocation();

            NoteSelected = NoteSelected ?? new Note();

            NoteSelected.Title      = Title;
            NoteSelected.Content    = Content;
            NoteSelected.CreatedAt  = DateTime.Now;
            NoteSelected.iNoteType  = (int)SelectedNoteType;
            NoteSelected.Longitude  = location.Longitude;
            NoteSelected.Latitude   = location.Latitude;

            //_noteService.SaveNote( NoteSelected );

            MessagingCenter.Instance.Send( this, "upsert", NoteSelected );

            await _navigation.PopAsync();
        }
qybjjes1

qybjjes11#

听起来像是在UI线程上,需要在不同的线程上运行代码。
使用Task.Run进入后台线程。
因为你在一个async方法中,并且你已经在MainThread上运行,所以这样做:

async Task MyMethod()
{
    // "await", so that "additional code" below is not run until this code finishes.
    // "async" is only needed if code in block uses "await".
    await Task.Run( async () =>
    {
        // code that needs to run on a background thread...
    });

    // additional code, that needs to run on the original thread...
    ...
}

在主线程上显式运行的替代方法

async Task MyMethod()
{
    // "await", so that "additional code" below is not run until this code finishes.
    // "async" is only needed if code in block uses "await".
    await Task.Run( async () =>
    {
        // code that needs to run on a background thread...
        // e.g. long-running logic that does not touch UI.
    });

    // "async" is only needed if code in block uses "await".
    await MainThread.InvokeOnMainThreadAsync( async () =>
    {
        // code that needs to run on MainThread (affects UI)...
    });
}

相关问题