321c4185a228c813d77cc465e84deb5c
SwiftUI CloudKit 完整项目 之 读取并显示公用数据 publicCloudDatabase

实战需求

SwiftUI CloudKit 完整项目 之 读取并显示公用数据 publicCloudDatabase

本文价值与收获

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

SwiftUI CloudKit 完整项目

SwiftUI CloudKit 完整项目

看完本文您将掌握的技能

  • CloudKit Dashboard 管理添加项目
  • 读取公开数据
  • 显示公开数据


基础配置

1. 配置icloud

配置icloud

配置icloud

2. 设置CloudKit Dashboard Record Type

设置CloudKit Dashboard Record Type

设置CloudKit Dashboard Record Type

3. 添加公共数据

截屏2021-06-22 下午9.45.22.png

截屏2021-06-22 下午9.45.22.png

实战代码

```
import SwiftUI

import Foundation
import CloudKit

let shoes_model = Shoes()

class Shoes: ObservableObject {
@Published var lists: [Shoe] = []
}

struct Shoe: Identifiable {
var id = UUID()
var recordID: CKRecord.ID?
//var brand: String = ""
var name: String = ""
//var size: Int = 0
}

class CKShoe {
static let database = CKContainer.default().publicCloudDatabase
// static let database = CKContainer.
class func fetch(completion: @escaping (Result<[Shoe], Error>) -> ()) {
print("demo start")
let predicate = NSPredicate(value: true)
let name = NSSortDescriptor(key: "name", ascending: true)
let query = CKQuery(recordType: "Shoes", predicate: predicate)
query.sortDescriptors = [name]

    let operation = CKQueryOperation(query: query)
    // operation.desiredKeys = ["brand", "name", "size"]
    operation.resultsLimit = 50

    var newShoes = [Shoe]()

    operation.recordFetchedBlock = { record in
        print("\(record["name"] as! String)")
        var shoe = Shoe()
        // shoe.recordID = record.recordID
top Created with Sketch.