美文网首页
WidgetKit框架详细解析(三) —— 一个基于Widget

WidgetKit框架详细解析(三) —— 一个基于Widget

作者: 刀客传奇 | 来源:发表于2020-11-20 09:25 被阅读0次

    版本记录

    版本号 时间
    V1.0 2020.11.20 星期五

    前言

    WidgetKit是iOS14的新的SDK,接下来几篇我们就一起看一下这个专题。感兴趣的可以看下面几篇文章。
    1. WidgetKit框架详细解析(一) —— 基本概览(一)
    2. WidgetKit框架详细解析(二) —— 一个基于WidgetKit和SwiftUI的简单示例(一)

    源码

    1. Swift

    首先看下工程组织结构

    下面就是源码了

    1. EmitronWidget.swift
    
    import WidgetKit
    import SwiftUI
    import Intents
    
    extension FileManager {
      static func sharedContainerURL() -> URL {
        return FileManager.default.containerURL(
          forSecurityApplicationGroupIdentifier: "group.emitron.contents"
        )!
      }
    }
    
    let snapshotEntry = WidgetContent(name: "iOS Concurrency with GCD and Operations",
      cardViewSubtitle: "iOS & Swift",
      descriptionPlainText: """
      Learn how to add concurrency to your apps! \
      Keep your app’s UI responsive to give your \
      users a great user experience.
      """,
      releasedAtDateTimeString: "Jun 23 2020 • Video Course (3 hrs, 21 mins)")
    
    //struct Provider: TimelineProvider {
    //  public typealias Entry = WidgetContent
    //
    //  public func snapshot(with context: Context, completion: @escaping (Entry) -> ()) {
    //    let entry = snapshotEntry
    //    completion(entry)
    //  }
    //
    //  func readContents() -> [Entry] {
    //    var contents: [WidgetContent] = []
    //    let archiveURL = FileManager.sharedContainerURL().appendingPathComponent("contents.json")
    //    print(">>> \(archiveURL)")
    //
    //    let decoder = JSONDecoder()
    //    if let codeData = try? Data(contentsOf: archiveURL) {
    //      do {
    //        contents = try decoder.decode([WidgetContent].self, from: codeData)
    //      } catch {
    //        print("Error: Can't decode contents")
    //      }
    //    }
    //    return contents
    //  }
    //
    //  public func timeline(with context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
    //    var entries = readContents()
    //
    //    // Generate a timeline by setting entry dates interval seconds apart,
    //    // starting from the current date.
    //    let currentDate = Date()
    //    let interval = 5
    //    for index in 0 ..< entries.count {
    //      entries[index].date = Calendar.current.date(byAdding: .second,
    //        value: index * interval, to: currentDate)!
    //    }
    //
    //    let timeline = Timeline(entries: entries, policy: .atEnd)
    //    completion(timeline)
    //  }
    //}
    
    struct PlaceholderView : View {
      var body: some View {
        EntryView(model: snapshotEntry)
      }
    }
    
    //@main
    //struct EmitronWidget: Widget {
    //  private let kind: String = "EmitronWidget"
    //
    //  public var body: some WidgetConfiguration {
    //    StaticConfiguration(kind: kind, provider: Provider(), placeholder: PlaceholderView()) { entry in
    //      EntryView(model: entry)
    //    }
    //    .configurationDisplayName("RW Tutorials")
    //    .description("See the latest video tutorials.")
    //    .supportedFamilies([.systemMedium])
    //  }
    //}
    
    struct Provider: IntentTimelineProvider {
      public typealias Entry = WidgetContent
    
      public func snapshot(for configuration: TimelineIntervalIntent, with context: Context, completion: @escaping (Entry) -> ()) {
        let entry = snapshotEntry
        completion(entry)
      }
    
      func readContents() -> [Entry] {
        var contents: [WidgetContent] = []
        let archiveURL = FileManager.sharedContainerURL().appendingPathComponent("contents.json")
        print(">>> \(archiveURL)")
    
        let decoder = JSONDecoder()
        if let codeData = try? Data(contentsOf: archiveURL) {
          do {
            contents = try decoder.decode([WidgetContent].self, from: codeData)
          } catch {
            print("Error: Can't decode contents")
          }
        }
        return contents
      }
    
      public func timeline(for configuration: TimelineIntervalIntent, with context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        var entries = readContents()
        let interval = configuration.interval as! Int
    
        // Generate a timeline consisting of five entries an hour apart, starting from the current date.
        let currentDate = Date()
        for index in 0 ..< entries.count {
          entries[index].date = Calendar.current.date(byAdding: .second, value: index * interval, to: currentDate)!
        }
    
        let timeline = Timeline(entries: entries, policy: .atEnd)
        completion(timeline)
      }
    }
    
    @main
    struct EmitronWidget: Widget {
      private let kind: String = "EmitronWidget"
    
      public var body: some WidgetConfiguration {
        IntentConfiguration(kind: kind, intent: TimelineIntervalIntent.self, provider: Provider(), placeholder: PlaceholderView()) { entry in
          EntryView(model: entry)
        }
        .configurationDisplayName("RW Tutorials")
        .description("See the latest video tutorials.")
        .supportedFamilies([.systemMedium])
      }
    }
    
    2. WidgetContent.swift
    
    import Foundation
    import WidgetKit
    
    struct WidgetContent: Codable, TimelineEntry {
      var date = Date()
      let name: String
      let cardViewSubtitle: String
      let descriptionPlainText: String
      let releasedAtDateTimeString: String
    }
    
    3. EntryView.swift
    
    import SwiftUI
    
    struct EntryView: View {
      let model: WidgetContent
    
      var body: some View {
        VStack(alignment: .leading) {
          Text(model.name)
            .font(.uiTitle4)
            .lineLimit(2)
            .fixedSize(horizontal: false, vertical: true)
            .padding([.trailing], 15)
            .foregroundColor(.titleText)
          
          Text(model.cardViewSubtitle)
            .font(.uiCaption)
            .lineLimit(nil)
            .foregroundColor(.contentText)
          
          Text(model.descriptionPlainText)
            .font(.uiCaption)
            .fixedSize(horizontal: false, vertical: true)
            .lineLimit(2)
            .lineSpacing(3)
            .foregroundColor(.contentText)
          
          Text(model.releasedAtDateTimeString)
            .font(.uiCaption)
            .lineLimit(1)
            .foregroundColor(.contentText)
        }
        .background(Color.cardBackground)
        .padding()
        .cornerRadius(6)
      }
    }
    

    后记

    本篇主要讲述了基于WidgetKitSwiftUI的简单示例,感兴趣的给个赞或者关注~~~

    相关文章

      网友评论

          本文标题:WidgetKit框架详细解析(三) —— 一个基于Widget

          本文链接:https://www.haomeiwen.com/subject/owwsqktx.html