iOS WidgetKit: remote images fails to load

后端 未结 2 1664
半阙折子戏
半阙折子戏 2020-12-17 18:29

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 an

相关标签:
2条回答
  • 2020-12-17 18:56

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

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

      OR

    2. 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)
    
    0 讨论(0)
  • 2020-12-17 18:58

    Got it: it's simply not supported and you aim to load images inside TimelineProvider:

    https://developer.apple.com/forums/thread/652581

    0 讨论(0)
提交回复
热议问题