【问题标题】:Dynamically display image in IOS xamarin - nitWithContentsOfFile:' method returned nil在 IOS xamarin 中动态显示图像 - nitWithContentsOfFile:' 方法返回 nil
【发布时间】:2017-03-13 14:23:32
【问题描述】:

我有一个可移植的 xamarin 应用程序,其中包含一些适用于 android 和 ios 的“特定覆盖”。

我有一个包含需要从服务器下载的图像的内容页面。 由于图像在服务器上不是“公开的”,我无法使用简单的 url 将图像添加到 Image 控件。 所以我的代码是下载图片,保存在本地,然后把图片的url传给Image控件:

        string filePath = GetThumbnailPath();
        Image img = new Image
        {
            HorizontalOptions = LayoutOptions.CenterAndExpand,
            WidthRequest = 150,
            HeightRequest = 150,
            Source =  FileImageSource.FromFile(filePath),
            Margin = new Thickness(0, 10, 0, 10)
        };     
        layout.Children.Add(img);

在 android 上一切正常。 在IOS上,图像保存到:

        string directory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        string filePath  = Path.Combine(directory, "thumbnail.jpg");

但是当页面加载时,应用程序崩溃: System.Exception:无法初始化“UIKit.UIImage”类型的实例:本机“initWithContentsOfFile:”方法返回 nil

我无法将图像更改为捆绑资源(其动态),也无法公开服务器调用(其处理程序需要标头参数或 cookie)

【问题讨论】:

    标签: xamarin xamarin.ios xamarin.forms


    【解决方案1】:

    在 iOS 上,您可以使用以下代码将图像保存到本地存储:

            var rootFolder = FileSystem.Current.LocalStorage;
            var folder = await rootFolder.CreateFolderAsync("Images", CreationCollisionOption.OpenIfExists);
    
            var file = await folder.CreateFileAsync("image.png", CreationCollisionOption.ReplaceExisting);
    
            var httpClient = new HttpClient();
            var buffer = await httpClient.GetByteArrayAsync(url);
    
            using (Stream stream = await file.OpenAsync(PCLStorage.FileAccess.ReadAndWrite))
            {
                stream.Write(buffer, 0, buffer.Length);
            }
    
            return file.Path;
    

    然后,您可以使用以下方式显示该图像:

            var imageSource = new FileImageSource { File = filePath};
            MyPicture.Source = imageSource;
    

    MyPicture 的定义是:

            <Image x:Name="MyPicture">
    

    【讨论】:

    • Nope...System.Exception:无法初始化“UIKit.UIImage”类型的实例:本机“initWithContentsOfFile:”方法返回 nil。可以通过将 MonoTouch.ObjCRuntime.Class.ThrowOnInitFailure 设置为 false 来忽略此条件。
    • 我从项目中复制/粘贴它,它按预期工作。您可以在演示项目中尝试它,如果它可以改变您在项目中使用它的方式。什么时候出现这个异常?
    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 2012-04-05
    • 2013-09-14
    相关资源
    最近更新 更多