356cf1867928d8372bf69702a0b9d3c3
SwiftUI Widget小组件和App之获取CPU利用率

实战需求

SwiftUI Widget小组件和App之获取CPU利用率

本文价值与收获

看完本文后,您将能够作出下面的界面

SwiftUI Widget小组件和App之获取CPU利用率

SwiftUI Widget小组件和App之获取CPU利用率

SwiftUI Widget小组件和App之获取CPU利用率

SwiftUI Widget小组件和App之获取CPU利用率

看完本文您将掌握的技能

1、显示Widget小组件
2、CPU利用率获取
3、动画奔跑猫


实战代码

1、主界面

import SwiftUI

struct CatRunningView: View {
    private let images = (0...4).map {
        Image(uiImage: UIImage(named: "\($0).png")!)
    }

    @EnvironmentObject var cpuUsageManager: CPUUsageManager

    var body: some View {
        VStack {
            // Cat running
            AnimatingImage(images: images,
                           interval: 0.02 * (100 - max(0.0, min(99.0, self.cpuUsageManager.cpuUsage))) / 6)

            // Total CPU usage
            Text("\(String(format: "%.1f", self.cpuUsageManager.cpuUsage))%")
                .font(Font.system(.title2, design: .rounded).monospacedDigit())

            // System and user CPU usage
            VStack {
                HStack {
                    Text("System: ")
                        .font(Font.system(.body, design: .rounded))
                    Text("\(String(format: "%.1f", self.cpuUsageManager.systemUsage))%")
                        .font(Font.system(.body, design: .rounded).monospacedDigit())
                        .foregroundColor(.red)
                }
                HStack {
                    Text("User: ")
                        .font(Font.system(.body, design: .rounded))
                    Text("\(String(format: "%.1f", self.cpuUsageManager.userUsage))%")
                        .font(Font.system(.body, design: .rounded).monospacedDigit())
                        .foregroundColor(.blue)
                }
            }.padding()
        }
    }
}

// MARK:- Preview
struct CatRunningView_Previews: PreviewProvider {
    static var previews: some View {
        CatRunningView()
            .environmentObject(CPUUsageManager())
    }
}

2、 cpu提取
```
import Foundation

class CPUUsageManager: ObservableObject {
@Published var cpuUsage: Double
@Published var systemUsage: Double
@Published var userUsage: Double

private weak var cpuTimer: Timer?

init() {
    let (system, user, _, _) = CPU.systemUsage()
    systemUsage = system
    userUsage = user
    cpuUsage = system + user
}

func start() {
top Created with Sketch.