iOS WidgetKit: remote images fails to load

后端 未结 2 1687
半阙折子戏
半阙折子戏 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)
    

提交回复
热议问题