项目作者: dmytro-anokhin

项目描述 :
SwiftUI view that makes loading content easy
高级语言: Swift
项目地址: git://github.com/dmytro-anokhin/remote-content-view.git
创建时间: 2020-08-09T22:51:04Z
项目社区:https://github.com/dmytro-anokhin/remote-content-view

开源协议:MIT License

下载


RemoteContentView

The RemoteContentView can download a remote content from a URL and display different loading states.

The package supports JSON and Plist (using Foundation Decodable protocol), images, and custom types.

You must provide a view to display the result value, and optionally a view for each loading state.

Loading and Displaying JSON Data

Displaying the list of posts received from the JSONPlaceholder API. The Post struct conforms to Codable protocol used for JSON decoding.

  1. struct Post : Codable {
  2. var id: Int
  3. var title: String
  4. var body: String
  5. }
  6. let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
  7. let content = DecodableRemoteContent(url: url, type: [Post].self, decoder: JSONDecoder())
  8. let view = RemoteContentView(remoteContent: content) { posts in
  9. List(posts, id: \Post.id) { post in
  10. VStack {
  11. Text(post.title)
  12. Text(post.body)
  13. }
  14. }
  15. }

Note, if you use default JSON decoder you can omit the last parameter:

  1. let content = DecodableRemoteContent(url: url, type: [Post].self)

Loading and Displaying an Image

  1. let url = URL(string: "http://optipng.sourceforge.net/pngtech/img/lena.png")!
  2. let remoteImage = RemoteImage(url: url)
  3. let view = RemoteContentView(remoteContent: remoteImage) {
  4. Image(uiImage: $0)
  5. }

Loading States

RemoteContentView supports 4 customizable loading states:

  1. let view = RemoteContentView(remoteContent: remoteContent,
  2. empty: {
  3. EmptyView()
  4. },
  5. progress: { progress in
  6. Text("Loading in progress: \(progress)")
  7. },
  8. failure: { error, retry in
  9. VStack {
  10. Text(error)
  11. Button("Retry", action: retry)
  12. }
  13. },
  14. content: { posts in
  15. List(posts, id: \Post.id) { post in
  16. VStack {
  17. Text(post.title)
  18. Text(post.body)
  19. }
  20. }
  21. })

Implementing Custom RemoteContent

The RemoteContent protocol defines objects that provide content and manage loading state.

  1. public protocol RemoteContent : ObservableObject {
  2. associatedtype Value
  3. associatedtype Progress
  4. var loadingState: RemoteContentLoadingState<Value, Progress> { get }
  5. func load()
  6. func cancel()
  7. }

The package provides two implementations:

  • DecodableRemoteContent for a content, loaded from a URL, represented by Decodable objects;
  • RemoteImage for images.

You can implement your own RemoteContent object if you need custom loading or to make the view work with existing content providers. You can find an example in CustomRemoteContent.playground.