Вы можете использовать dependencyService , чтобы получить путь к файлу pdf из приложения iOS и Android.
Интерфейс:
public interface IGetPdfFilePath
{
string filePath(string fileName);
}
Получить путь к файлу в Xamarin.forms:
string pdfPath = DependencyService.Get<IGetPdfFilePath>().filePath("myPdf.pdf");
Console.WriteLine(pdfPath);
В iOS путь зависит от того, где вы храните файл:
[assembly: Dependency (typeof (GetPdfFilePath_iOS))]
namespace UsingDependencyService.iOS
{
public class GetPdfFilePath_iOS : IGetPdfFilePath
{
public GetPdfFilePath_iOS ()
{
}
public string filePath(string fileName)
{
// 1. if your store your pdf in DocumentDirectory
//string directories = NSSearchPath.GetDirectories(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.All)[0];
//string pathBundle = directories + "/" + fileName;
////bool fileExists = NSFileManager.DefaultManager.FileExists(pathBundle);
//return pathBundle;
//2.pdf file in your project
string pathBundle = Path.Combine(NSBundle.MainBundle.ResourcePath, fileName);
return pathBundle;
}
}
}
В Android:
[assembly: Dependency(typeof(GetPdfFilePath_Android))]
namespace UsingDependencyService.Android
{
public class GetPdfFilePath_Android : Java.Lang.Object, IGetPdfFilePath
{
public string filePath(string fileName)
{
string internalstorageurl = string.Format("file:///android_asset/Content/{0}", WebUtility.UrlEncode(fileName));
return internalstorageurl;
}
}
}
Обновление
Добавьте эту строку: [assembly: Dependency(typeof(GetPdfFilePath_Android))]
в ваш класс Android. GetPdfFilePath_Android
вот имя вашего класса.
Другим способом является создание собственного средства визуализации вашего веб-вида, вы можете взглянуть на этот проект .
Обновление для проверки файла: , я добавляю этот метод в Android, чтобы проверить, существует ли файл внутри Assets/Content
.
public bool fileExist (string fileName) {
AssetManager assets = MainActivity.Instance.Assets;
string[] names = assets.List("Content");
for (int i = 0; i < names.Length; i++)
{
if (names[i] == fileName)
{
return true;
}
}
return false;
}
Примечание: Вы должны изменить действие сборки файла pdf
на AndroidAsset
, если вы не можете найти файл внутри Активов.