iOS架构

iOS-Widget小组件开发实战与问题解决

2023-08-10  本文已影响0人  梵生

文档

官方介绍
官方文档
官方文档-可用组件
官方文档翻译-非最新
官方文档-用户交互指南
主要参考文档
修改为IntentConfiguration
简单demo
各种widget效果demo

开发须知

核心代码解释

// 入口代码,如果需要支持多个相同尺寸的不同widget,需要在这里添加widget2(),widget3()..
// 每个widget,都可以支持小中大三种尺寸
@main
struct widgetBundle: WidgetBundle {
    var body: some Widget {
        widget()
        widget2()
        widgetLiveActivity()
    }
}
// widget组件
struct widget: Widget {
    // widget唯一标识符
//    let kind: String = FSWidgetKindString
    let kind: String = "com.company.project.widget"

    // 添加 widgetEntryView 为 widget 的视图
    // supportedFamilies,设定当前widget支持的尺寸,可以设置小中大三种
    // configurationDisplayName,显示在小组件库中的名字
    // description,显示在小组件库中的描述
    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: Provider()) { entry in
            widgetEntryView(entry: entry)
        }.supportedFamilies([.systemMedium])
        .configurationDisplayName("WidgetDemo")
        .description("New Message")
    }
}
// 时间线更新
struct Provider: TimelineProvider {
    // 显示到主屏幕,等待数据加载,显示的内容
    func placeholder(in context: Context) -> SimpleEntry {
        SimpleEntry(date: Date(), image: UIImage(named: "placeholder")!)
    }

    // 预览和小组件库中的显示
    func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) {
        let entry = SimpleEntry(date: Date(), image: UIImage(named: "placeholder")!)
        completion(entry)
    }

    // **最重要的方法**,后续生成新的entry,用于刷新界面,都是在这里完成
    func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        
        // 或者发起API请求,回调请求内设置 timeline的更新策略
        // API.fetchData{ result in }
        
        // 每分钟更新一次
        let currentDate = Date()
        let updateDate = Calendar.current.date(byAdding: .minute, value: 1, to: currentDate)!
        
        // 生成新的entry数据
        let entry = SimpleEntry(date: Date(), image: UIImage(named: "placeholder")!)
        
        let timeline = Timeline(entries: [entry], policy: .after(updateDate))
        completion(timeline)
    }
}
// 更新widget所需要的所有数据
struct SimpleEntry: TimelineEntry {
    let date: Date
    let image: UIImage    // 当前需要展示的图片
}
// widget显示的内容,可以针对不同大小的widget设置不同的View
struct widgetEntryView: View {
    var entry: Provider.Entry

    @Environment(\.widgetFamily) var family

    @ViewBuilder
    var body: some View {
        switch family {
        case .systemSmall:
            // 小,只支持widgetURL,点击widget跳转指定scheme
            ZStack {
                Image(uiImage: entry.image)
                            .resizable()
                            .scaledToFill()
            }.widgetURL(URL(string: "demoapp://homepage")!)

        case .systemMedium:
            // 中,同时支持Link和widgetURL
            ZStack {
                Image(uiImage: entry.image)
                            .resizable()
                            .scaledToFill()
                Link(destination: URL(string: "demoapp://link")!) {
                    Text("点击跳转")
                }
            }.widgetURL(URL(string: "demoapp://homepage")!)

        default:
            // 大,同时支持Link和widgetURL
            ZStack {
                Image(uiImage: entry.image)
                            .resizable()
                            .scaledToFill()
                Link(destination: URL(string: "demoapp://link")!) {
                    Text("点击跳转")
                }
            }.widgetURL(URL(string: "demoapp://homepage")!)
        }
    }
}

与主App通过Group共享数据

// UserDefault 共享
let DRGroupDefaultSuitName = "group.com.demo"

func DRGroupDefault() -> UserDefaults {
    return UserDefaults(suiteName: DRGroupDefaultSuitName)!
}

func DRGroupDefaultSet(_ value: Any?, forKey defaultName: String) {
    DRGroupDefault().set(value, forKey: defaultName)
}

func DRGroupDefaultObject(forKey defaultName: String) -> Any? {
    return DRGroupDefault().object(forKey: defaultName)
}

func DRGroupDefaultBool(forKey defaultName: String) -> Bool {
    return DRGroupDefault().bool(forKey: defaultName)
}

func DRGroupDefaultSynchronize() {
    let userDefault: UserDefaults = DRGroupDefault()
    
    if Thread.isMainThread {
        NSObject.cancelPreviousPerformRequests(withTarget: userDefault, selector: #selector(userDefault.synchronize), object: nil)
        userDefault.perform(#selector(userDefault.synchronize), with: nil, afterDelay: 2.0)
    } else {
        userDefault.synchronize()
    }
}
// File 文件共享
let DRGroupFileIdentifier = "group.com.demo"

func DRGroupFileURL() -> URL? {
    return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: DRGroupFileIdentifier)
}

func DRGroupFileWrite(toFile fileName: String, content: String) -> Bool {
    guard let groupURL = DRGroupFileURL() else {
        return false
    }
    
    let fileURL = groupURL.appendingPathComponent(fileName)
    print(fileURL)
    
    if DRFileManager.isExist(atPath: fileURL.absoluteString) {
        DRFileManager.removeItem(atPath: fileURL.absoluteString)
    }

    do {
        try content.write(to: fileURL, atomically: true, encoding: .utf8)
        print("writeDataToFile 写入文件成功")
        return true
    } catch {
        print("writeDataToFile 写入文件失败")
        return false
    }
}

func DRGroupFileRead(fromFile fileName: String) -> String {
    guard let groupURL = DRGroupFileURL() else {
        return ""
    }
    
    let fileURL = groupURL.appendingPathComponent(fileName)
    print(fileURL)
    
    guard let contentData = FileManager.default.contents(atPath: fileURL.path) else {
        return ""
    }
    let content = String(data: contentData, encoding: .utf8)
    return content ?? ""
}

主App基于UIKit实现View,widget引入图片

// 主App
public struct TestPainting {
    
    static func uiKitView() -> UIView {
        let view = UIImageView.init(frame: CGRect(x: 0, y: 0, width: DRHelper.screen_width, height: 180))
        view.backgroundColor = .cyan
        view.roundingCorners(corners: .allCorners, radii: 20)
        
        let image = UIImage(named: "icon_placeholder")
        view.image = image
        view.contentMode = .center
        
        return view
    }
    
    
    public static func uiKitContextImage() -> UIImage? {
        let  imageView = self.uiKitView()
        let image = imageView.toImage()
        return image
    }
    
}

extension UIView {
    func toImage() -> UIImage? {
        let scale = UIScreen.main.scale
        UIGraphicsBeginImageContextWithOptions(self.frame.size, false, scale)
        guard let context = UIGraphicsGetCurrentContext() else {
            UIGraphicsEndImageContext()
            return nil
        }
        self.layer.render(in: context)
        let viewImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return viewImage
    }
}
// widget
struct widgetEntryView : View {
    var entry: Provider.Entry

    var body: some View {
        ZStack {
            let image = TestPainting.uiKitContextImage()
            Image(uiImage: image ?? UIImage(named: "placeholder")!)
                .resizable()
                .scaledToFill()
        }.widgetURL(URL(string: "demo://homepage")!)
    }
}
    // 主App 判断是否添加了小组件
    static func isWidgetExist(complete: @escaping (_ exist: Bool) -> Void) {
        WidgetCenter.shared.getCurrentConfigurations { result in
            var exist = false
            defer {
                complete(exist)
            }
            guard case let .success(widgets) = result else {
                return
            }
            let currentWidget = widgets.first(where: { widget in
                debugPrint("小组件名称:\(widget.kind)")
                return widget.kind == DRConstantKey.widgetKindString
            })
            if currentWidget != nil {
                exist = true
            }
        }
    }

真机运行报错

上一篇 下一篇

猜你喜欢

热点阅读