Проблемы с попыткой определить, что телефон iOS молчит? - PullRequest
2 голосов
/ 16 июня 2020

Я вызываю этот метод, чтобы попытаться определить, не работает ли iOS устройство. Однако, похоже, он не может его обнаружить, хотя если я поставлю здесь точку останова "silentText =" Silent Mode On. ", Тогда он перейдет к этой точке. Однако он все равно возвращает пустую строку.

Имеет у кого-то есть идеи, что может пойти не так с этим способом возврата значения silentText. Я думаю, что, возможно, это связано с тем, как я бегу и возвращаю значение из задачи.

    SilentModeText = await DependencyService.Get<ISoundMethods>().IsDeviceSilent();

    public async Task<string> IsDeviceSilent()
    {
        AVAudioSession.SharedInstance().SetActive(true);
        var outputVolume = AVAudioSession.SharedInstance().OutputVolume;
        if ((int)(outputVolume * 100) == 0)
            return "Phone volume is set to silent. Please adjust volume higher if you want the phrases and meanings to be read aloud.";
        else if (outputVolume * 100 < 30)
            return "Phone volume set low. Please adjust volume higher if you want the phrases and meanings to be read aloud.";

        var soundFilePath = NSBundle.MainBundle.PathForResource("Audio/mute", "caf");
        var sound = new SystemSound(new NSUrl(soundFilePath, false));
        DateTime startTime = DateTime.Now;
        var silentText = "";
        sound.AddSystemSoundCompletion(async () =>
        {
            var endTime = DateTime.Now;
            var timeDelta = (endTime - startTime).Milliseconds;
            if (timeDelta < 100)
            {
                silentText = "Silent Mode On. Please turn off the Silent Mode switch at the top left side of the phone if you want to listen to the phrases and meanings using the phone speaker.";
            }
            else {
                silentText = "Silent Mode Off";
            }
        });
        sound.PlaySystemSound();
        return silentText;
    }

1 Ответ

1 голос
/ 17 июня 2020

Вы можете использовать TaskCompletionSource для возврата результата метода asyn c.

Измените реализацию, как показано ниже

   public Task<string> IsDeviceSilent()
    {

        var tcs = new TaskCompletionSource<string>();

        AVAudioSession.SharedInstance().SetActive(true);
        var outputVolume = AVAudioSession.SharedInstance().OutputVolume;
        if ((int)(outputVolume * 100) == 0) { 
            string result = "Phone volume is set to silent. Please adjust volume higher if you want the phrases and meanings to be read aloud.";
            tcs.SetResult(result);
        }                 
        else if (outputVolume * 100 < 30)
        {
            string result = "Phone volume set low. Please adjust volume higher if you want the phrases and meanings to be read aloud.";
            tcs.SetResult(result);
        }
        else
        {
            var soundFilePath = NSBundle.MainBundle.PathForResource("Audio/mute", "caf");
            var sound = new SystemSound(new NSUrl(soundFilePath, false));
            DateTime startTime = DateTime.Now;

            sound.AddSystemSoundCompletion(() =>
            {
                var endTime = DateTime.Now;
                var timeDelta = (endTime - startTime).Milliseconds;

                string silentText = null;

                if (timeDelta < 100)
                {
                    silentText = "Silent Mode On. Please turn off the Silent Mode switch at the top left side of the phone if you want to listen to the phrases and meanings using the phone speaker.";
                }
                else
                {
                    silentText = "Silent Mode Off";
                }

                tcs.SetResult(silentText);
            });
            sound.PlaySystemSound();

        }

        return tcs.Task;
    }

Вызов в формах

  SilentModeText = await DependencyService.Get<ISoundMethods>().IsDeviceSilent();

Ссылка: { ссылка }.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...