Xamarin.Forms
Gestion des exceptions
Recherche…
Une façon de signaler les exceptions sur iOS
Accédez au fichier Main.cs
dans le projet iOS et modifiez le code existant, comme présenté ci-dessous:
static void Main(string[] args)
{
try
{
UIApplication.Main(args, null, "AppDelegate");
}
catch (Exception ex)
{
Debug.WriteLine("iOS Main Exception: {0}", ex);
var watson = new LittleWatson();
watson.SaveReport(ex);
}
}
ILittleWatson
interface ILittleWatson
, utilisée dans le code portable, pourrait ressembler à ceci:
public interface ILittleWatson
{
Task<bool> SendReport();
void SaveReport(Exception ex);
}
Implémentation pour projet iOS :
[assembly: Xamarin.Forms.Dependency(typeof(LittleWatson))]
namespace SomeNamespace
{
public class LittleWatson : ILittleWatson
{
private const string FileName = "Report.txt";
private readonly static string DocumentsFolder;
private readonly static string FilePath;
private TaskCompletionSource<bool> _sendingTask;
static LittleWatson()
{
DocumentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
FilePath = Path.Combine(DocumentsFolder, FileName);
}
public async Task<bool> SendReport()
{
_sendingTask = new TaskCompletionSource<bool>();
try
{
var text = File.ReadAllText(FilePath);
File.Delete(FilePath);
if (MFMailComposeViewController.CanSendMail)
{
var email = ""; // Put receiver email here.
var mailController = new MFMailComposeViewController();
mailController.SetToRecipients(new string[] { email });
mailController.SetSubject("iPhone error");
mailController.SetMessageBody(text, false);
mailController.Finished += (object s, MFComposeResultEventArgs args) =>
{
args.Controller.DismissViewController(true, null);
_sendingTask.TrySetResult(true);
};
ShowViewController(mailController);
}
}
catch (FileNotFoundException)
{
// No errors found.
_sendingTask.TrySetResult(false);
}
return await _sendingTask.Task;
}
public void SaveReport(Exception ex)
{
var exceptionInfo = $"{ex.Message} - {ex.StackTrace}";
File.WriteAllText(FilePath, exceptionInfo);
}
private static void ShowViewController(UIViewController controller)
{
var topController = UIApplication.SharedApplication.KeyWindow.RootViewController;
while (topController.PresentedViewController != null)
{
topController = topController.PresentedViewController;
}
topController.PresentViewController(controller, true, null);
}
}
}
Et puis, quelque part, là où l'application démarre, mettez:
var watson = DependencyService.Get<ILittleWatson>();
if (watson != null)
{
await watson.SendReport();
}
Modified text is an extract of the original Stack Overflow Documentation
Sous licence CC BY-SA 3.0
Non affilié à Stack Overflow