iOS WidgetKit:远程图像无法加载 [英] iOS WidgetKit: remote images fails to load

查看:102
本文介绍了iOS WidgetKit:远程图像无法加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我观察到一个奇怪的事情:在新的小部件中,经常会远程图像无法显示,即使该图像已成功加载并放置在缓存中.

I'm observing a bizarre thing: in the new widgets far too often remote images are not being displayed even though the image has been successfully loaded and placed in cache.

对于图像下载,我尝试过:

For image downloading I've tried:

  • SDWebImageSwiftUI
  • 翠鸟
  • SwURL

所有这些都表明图像加载成功,但是实际的窗口小部件未显示该图像.

All of them indicate that image loading succeed, but the actual widget is not showing it.

struct TestWidgetEntryView : View {
    var entry: Provider.Entry

    var body: some View {
        WebImage(url: URL(string: "https://miro.medium.com/max/3840/0*TLqp5Uwavd-U_xrs.jpg"))
                        .onSuccess()
                        .resizable()
    }
}

在调试器的第二次运行中-从缓存中加载图像-我得到了显示的图像,但是在初始运行时从不显示(?).

On the second run of the debugger - with image loading from cache - I get the image displayed, but never(?) on initial run.

感觉就像在onSuccess中,我需要触发UI无效吗?但是如何?

It feels like that in onSuccess I need to trigger UI-invalidation? But how?

(因为实际上碰巧我尝试过的每个图像库-我都不认为库中有问题)

(Since it happens to literally every image-lib I try - I don't think that it's something off in the libs)

环境:

  • iOS 14 Beta 3(设备和模拟器)
  • Xcode 12 Beta 3
  • 在调试过程中,内存使用量约为15mb

推荐答案

是的,正如康斯坦丁(Konstantin)所述,不支持异步加载图像.有2个选项可在小部件中加载网络图像

Yes, as mentioned by Konstantin, it is not supported to load images asynchronously. There are 2 options to load network image in widgets

  1. 要么在 TimelineProvider 中获取所有图像,然后将它们直接注入视图.

  1. Either fetch all the images in TimelineProvider and inject them to the views directly.

OR

使用Data(contentsOf: url)来获取图像.这样,它仍然可以同步获取它们,但是代码更干净.示例代码-

Use Data(contentsOf: url) to fetch the image. This way it still fetches them synchronously but the code is cleaner. Sample code -

struct NetworkImage: View {

  private let url: URL?

  var body: some View {

    Group {
     if let url = url, let imageData = try? Data(contentsOf: url), 
       let uiImage = UIImage(data: imageData) {

       Image(uiImage: uiImage)
         .resizable()
         .aspectRatio(contentMode: .fill)
      } 
      else {
       Image("placeholder-image")
      }
    }
  }

}

此视图可以像这样简单地使用-

This view can simply be use like this -

NetworkImage(url: url)

这篇关于iOS WidgetKit:远程图像无法加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆