2022-06-08 19:24:01 +02:00
using System ;
using System.Threading ;
using System.Threading.Tasks ;
2022-07-07 21:24:29 +02:00
using Bit.Core.Services ;
2022-06-08 19:24:01 +02:00
using UIKit ;
using Xamarin.Forms ;
using Xamarin.Forms.Platform.iOS ;
namespace Bit.iOS.Core.Utilities
{
public static class ImageSourceExtensions
{
/// <summary>
/// Gets the native image from the ImageSource.
/// Taken from https://github.com/xamarin/Xamarin.Forms/blob/02dee20dfa1365d0104758e534581d1fa5958990/Xamarin.Forms.Platform.iOS/Renderers/ImageElementManager.cs#L264
/// </summary>
public static async Task < UIImage > GetNativeImageAsync ( this ImageSource source , CancellationToken cancellationToken = default ( CancellationToken ) )
{
if ( source = = null | | source . IsEmpty )
2022-07-07 21:24:29 +02:00
{
2022-06-08 19:24:01 +02:00
return null ;
2022-07-07 21:24:29 +02:00
}
2022-06-08 19:24:01 +02:00
var handler = Xamarin . Forms . Internals . Registrar . Registered . GetHandlerForObject < IImageSourceHandler > ( source ) ;
if ( handler = = null )
2022-07-07 21:24:29 +02:00
{
LoggerHelper . LogEvenIfCantBeResolved ( new InvalidOperationException ( "GetNativeImageAsync failed cause IImageSourceHandler couldn't be found" ) ) ;
2022-06-08 19:24:01 +02:00
return null ;
2022-07-07 21:24:29 +02:00
}
2022-06-08 19:24:01 +02:00
try
{
float scale = ( float ) UIScreen . MainScreen . Scale ;
return await handler . LoadImageAsync ( source , scale : scale , cancelationToken : cancellationToken ) ;
}
catch ( OperationCanceledException )
{
2022-07-07 21:24:29 +02:00
LoggerHelper . LogEvenIfCantBeResolved ( new OperationCanceledException ( "GetNativeImageAsync was cancelled" ) ) ;
2022-06-08 19:24:01 +02:00
}
catch ( Exception ex )
{
2022-07-07 21:24:29 +02:00
LoggerHelper . LogEvenIfCantBeResolved ( new InvalidOperationException ( "GetNativeImageAsync failed" , ex ) ) ;
2022-06-08 19:24:01 +02:00
}
return null ;
}
}
}