繁体   English   中英

如何从任务中返回值 <string> 在我的iOS Dependecy服务[Xamarin.Forms.iOS]中?

[英]How can I return the value from my Task<string> in my iOS Dependecy Service [Xamarin.Forms.iOS]?

我正在运行一个可以正常工作的函数,并且得到了正确的值,但是在弄清楚如何从我的DI服务中将值(即带有文本的字符串)返回到共享代码时遇到了问题。 当我在下面的函数中的日志中输入结果时,我得到正确的值:

RecognitionTask = SpeechRecognizer.GetRecognitionTask (LiveSpeechRequest, (SFSpeechRecognitionResult result, NSError err) =>
        {
            thetextresult = result.BestTranscription.FormattedString;
            System.Diagnostics.Debug.WriteLine(thetextresult); //I get the correct value
        });

(如果我等待上面的这段代码可以解决我的问题吗?如果可以,我如何等待字符串的结果?)

我当前的问题是,在此代码之后,我再次使用日志,以查看在此功能之后是否可以再次访问日志:

System.Diagnostics.Debug.WriteLine("Do I reach this?");

但是我无法做到这一点,因此无法达到函数末尾的return thetextresult ,这意味着我无法在共享代码中获得回报。

代码如下所示:

我的iOS DependecyService中的功能:

        var node = AudioEngine.InputNode;
        var recordingFormat = node.GetBusOutputFormat(0);

        node.InstallTapOnBus(0, 1024, recordingFormat, (AVAudioPcmBuffer buffer, AVAudioTime when) =>
        {
            LiveSpeechRequest.Append(buffer);
        });

        AudioEngine.Prepare();
        NSError error;
        AudioEngine.StartAndReturnError(out error);

        RecognitionTask = SpeechRecognizer.GetRecognitionTask (LiveSpeechRequest, (SFSpeechRecognitionResult result, NSError err) =>
        {
            thetextresult = result.BestTranscription.FormattedString;
            System.Diagnostics.Debug.WriteLine(thetextresult); //value gets out correctly.
        });


    }

  System.Diagnostics.Debug.WriteLine("Do I reach this?"); //this does not get reached when i do the function.
  return thetextresult; //which means that this is not returning the value
}

接口:

public interface ISoundToSpeak
{
    Task<string> SpeechToTextAsync();
}

我如何在我的内容页面上使用它,功能:

async Task <string>WaitForSpeech()
    {
        return await DependencyService.Get<ISoundToSpeak>().SpeechToTextAsync();
    }

一个按钮:

async void speakClick(object s, EventArgs a)
    {
        var speechText = await WaitForSpeech();
        System.Diagnostics.Debug.WriteLine(speechText); //so with this current code i do not get the text out in my shared code. 
    }

您的函数StartRecord是异步的,但是我看不到其中的任何等待。 SpeechRecognizer.GetRecognitionTask是带有回调的任务。 您应该能够达到“我能达到这个目标吗?” 但是textresult的结果不会出现,因为您不必等到GetRecognitionTask完成。 您应该以某种方式在RecognitionTask上等待,或者不从函数返回textresult,而是从回调中调用共享代码。

最后起作用的是为SpeechToTextAsync提供回调函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM