-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathCloudKitSharing.swift
More file actions
477 lines (445 loc) · 16.3 KB
/
CloudKitSharing.swift
File metadata and controls
477 lines (445 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
#if canImport(CloudKit)
import CloudKit
import Dependencies
import SwiftUI
#if canImport(UIKit)
import UIKit
#endif
/// A shared record that can be used to present a ``CloudSharingView``.
///
/// See <doc:CloudKitSharing#Creating-CKShare-records> for more information.,
@available(iOS 15, tvOS 15, macOS 12, watchOS 8, *)
public struct SharedRecord: Hashable, Identifiable, Sendable {
let container: any CloudContainer
public let share: CKShare
public var id: CKRecord.ID { share.recordID }
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.container === rhs.container && lhs.share == rhs.share
}
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(container))
hasher.combine(share)
}
}
@available(iOS 17, macOS 14, tvOS 17, watchOS 10, *)
extension SyncEngine {
private struct SharingError: LocalizedError {
enum Reason {
case shareCouldNotBeCreated
case recordMetadataNotFound
case recordNotRoot([ForeignKey])
case recordTableNotSynchronized
case recordTablePrivate
case syncEngineNotRunning
}
var recordTableName: String?
var recordPrimaryKey: String?
let reason: Reason
let debugDescription: String
var errorDescription: String? {
"The record could not be shared."
}
}
/// Shares a record in CloudKit.
///
/// This method will thrown an error if:
///
/// * The table the `record` belongs to is not synchronized to CloudKit.
/// * The `record` has any foreign keys. Only root records are shareable in CloudKit.
/// * The table the `record` belongs to is a "private" table as determined by the
/// [`SyncEngine` initializer](<doc:SyncEngine/init(for:tables:privateTables:containerIdentifier:defaultZone:startImmediately:delegate:logger:)>).
/// * The `record` is being shared before it has been synchronized to CloudKit.
/// * Any of the CloudKit APIs invoked throw an error.
///
/// The value returned from this method can be used to present a ``CloudSharingView`` which
/// allows the user to send a share URL to another user.
///
/// - Parameters:
/// - record: The record to be shared on CloudKit.
/// - configure: A trailing closure that can customize the `CKShare` sent to CloudKit. See
/// [Apple's documentation](https://developer.apple.com/documentation/cloudkit/ckshare/systemfieldkey)
/// for more info on what can be configured.
public func share<T: PrimaryKeyedTable>(
record: T,
configure: @Sendable (CKShare) -> Void
) async throws -> SharedRecord
where T.TableColumns.PrimaryKey.QueryOutput: IdentifierStringConvertible {
guard isRunning
else {
throw SharingError(
reason: .syncEngineNotRunning,
debugDescription: """
Sync engine is not running. Make sure engine is running by invoking the 'start()' \
method, or using the 'startImmediately' argument when initializing the engine.
"""
)
}
guard tablesByName[T.tableName] != nil
else {
throw SharingError(
recordTableName: T.tableName,
recordPrimaryKey: record.primaryKey.rawIdentifier,
reason: .recordTableNotSynchronized,
debugDescription: """
Table is not shareable: table type not passed to 'tables' parameter of \
'SyncEngine.init'.
"""
)
}
if let foreignKeys = foreignKeysByTableName[T.tableName], !foreignKeys.isEmpty {
throw SharingError(
recordTableName: T.tableName,
recordPrimaryKey: record.primaryKey.rawIdentifier,
reason: .recordNotRoot(foreignKeys),
debugDescription: """
Only root records are shareable, but parent record(s) detected via foreign key(s).
"""
)
}
guard !privateTables.contains(where: { T.self == $0.base })
else {
throw SharingError(
recordTableName: T.tableName,
recordPrimaryKey: record.primaryKey.rawIdentifier,
reason: .recordTablePrivate,
debugDescription: """
Private tables are not shareable: table type passed to 'privateTables' parameter of \
'SyncEngine.init'.
"""
)
}
let recordName = record.recordName
let lastKnownServerRecord = try await {
let lastKnownServerRecord =
try await metadatabase.read { db in
try SyncMetadata
.where { $0.recordName.eq(recordName) }
.select(\._lastKnownServerRecordAllFields)
.fetchOne(db)
} ?? nil
guard let lastKnownServerRecord
else {
throw SharingError(
recordTableName: T.tableName,
recordPrimaryKey: record.primaryKey.rawIdentifier,
reason: .recordMetadataNotFound,
debugDescription: """
No sync metadata found for record. Has the record been saved to the database \
and synchronized to iCloud? Invoke 'SyncEngine.sendChanges()' to force \
synchronization.
"""
)
}
return try await container.database(for: lastKnownServerRecord.recordID)
.record(for: lastKnownServerRecord.recordID)
}()
var existingShare: CKShare? {
get async throws {
let share = try await metadatabase.read { db in
try SyncMetadata
.find(lastKnownServerRecord.recordID)
.select(\.share)
.fetchOne(db) ?? nil
}
guard let shareRecordID = share?.recordID
else {
return nil
}
do {
return try await container.database(for: lastKnownServerRecord.recordID)
.record(for: shareRecordID) as? CKShare
} catch let error as CKError where error.code == .unknownItem {
return nil
}
}
}
let sharedRecord =
try await existingShare
?? CKShare(
rootRecord: lastKnownServerRecord,
shareID: CKRecord.ID(
recordName: "share-\(recordName)",
zoneID: lastKnownServerRecord.recordID.zoneID
)
)
configure(sharedRecord)
let (saveResults, _) = try await container.privateCloudDatabase.modifyRecords(
saving: [sharedRecord, lastKnownServerRecord],
deleting: []
)
let savedShare = try saveResults.values.compactMap { result in
let record = try result.get()
return record.recordID == sharedRecord.recordID ? record as? CKShare : nil
}
.first
let savedRootRecord = try saveResults.values.compactMap { result in
let record = try result.get()
return record.recordID == lastKnownServerRecord.recordID ? record : nil
}
.first
guard let savedShare, let savedRootRecord
else {
throw SharingError(
recordTableName: T.tableName,
recordPrimaryKey: record.primaryKey.rawIdentifier,
reason: .shareCouldNotBeCreated,
debugDescription: """
A 'CKShare' could not be created in iCloud.
"""
)
}
try await userDatabase.write { db in
try SyncMetadata
.where { $0.recordName.eq(recordName) }
.update {
$0.setLastKnownServerRecord(savedRootRecord)
$0.share = #bind(savedShare)
}
.execute(db)
}
return SharedRecord(container: container, share: savedShare)
}
public func unshare<T: PrimaryKeyedTable>(record: T) async throws
where T.TableColumns.PrimaryKey.QueryOutput: IdentifierStringConvertible {
let share = try await metadatabase.read { [recordName = record.recordName] db in
try SyncMetadata
.where { $0.recordName.eq(recordName) }
.select(\.share)
.fetchOne(db)
?? nil
}
guard let share
else {
reportIssue(
"""
No share found associated with record.
"""
)
return
}
try await unshare(share: share)
}
func unshare(share: CKShare) async throws {
let result = try await syncEngines.private?.database.modifyRecords(
saving: [],
deleting: [share.recordID]
)
try result?.deleteResults.values.forEach { _ = try $0.get() }
}
/// Accepts a shared record.
///
/// This method should be invoked from various delegate methods on the scene delegate of the
/// app. See <doc:CloudKitSharing#Accepting-shared-records> for more info.
public func acceptShare(metadata: CKShare.Metadata) async throws {
try await acceptShare(metadata: ShareMetadata(rawValue: metadata))
}
}
#if canImport(UIKit) && !os(tvOS) && !os(watchOS)
/// A view that presents standard screens for adding and removing people from a CloudKit share \
/// record.
///
/// See <doc:CloudKitSharing#Creating-CKShare-records> for more info.
@available(iOS 17, macOS 14, tvOS 17, *)
public struct CloudSharingView: View {
let sharedRecord: SharedRecord
let availablePermissions: UICloudSharingController.PermissionOptions
let didFinish: (Result<Void, Error>) -> Void
let didStopSharing: () -> Void
let syncEngine: SyncEngine
@Dependency(\.context) var context
@Environment(\.dismiss) var dismiss
public init(
sharedRecord: SharedRecord,
availablePermissions: UICloudSharingController.PermissionOptions = [],
didFinish: @escaping (Result<Void, Error>) -> Void = { _ in },
didStopSharing: @escaping () -> Void = {},
syncEngine: SyncEngine = {
@Dependency(\.defaultSyncEngine) var defaultSyncEngine
return defaultSyncEngine
}()
) {
self.sharedRecord = sharedRecord
self.didFinish = didFinish
self.didStopSharing = didStopSharing
self.availablePermissions = availablePermissions
self.syncEngine = syncEngine
}
public var body: some View {
if context == .live {
CloudSharingViewRepresentable(
sharedRecord: sharedRecord,
availablePermissions: availablePermissions,
didFinish: didFinish,
didStopSharing: didStopSharing,
syncEngine: syncEngine
)
} else {
NavigationStack {
Form {
VStack(alignment: .center, spacing: 10) {
Group {
if let data = sharedRecord.share[CKShare.SystemFieldKey.thumbnailImageData]
as? Data,
let uiImage = UIImage(data: data)
{
Image(uiImage: uiImage)
} else {
Text("☁️")
}
}
.font(.system(size: 96))
Text(
sharedRecord.share[CKShare.SystemFieldKey.title] as? String
?? "Share"
)
.font(.title.weight(.semibold))
}
.frame(maxWidth: .infinity)
.listRowBackground(Color.clear)
Section {
HStack {
Image(systemName: "person.crop.circle.fill")
.imageScale(.large)
.font(.title)
.foregroundStyle(
Gradient(colors: [
Color(red: 0.7, green: 0.75, blue: 0.9),
Color(red: 0.4, green: 0.45, blue: 0.6),
])
)
NavigationLink("(Owner)", value: Bool?.none)
}
}
Section {
VStack(alignment: .leading) {
Text("\(Image(systemName: "eye.fill")) Share Preview")
.font(.headline)
Text(
"""
This is a mock screen used only in previews. You are not interacting with iCloud.
"""
)
.font(.callout)
.foregroundStyle(.gray)
}
}
Button("Stop Sharing", role: .destructive) {
Task {
try await syncEngine.unshare(share: sharedRecord.share)
try await syncEngine.fetchChanges()
dismiss()
}
}
.frame(maxWidth: .infinity)
}
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button {
dismiss()
} label: {
Image(systemName: "checkmark")
.font(.headline)
.foregroundStyle(.white)
.padding(6)
.background(Circle().fill(.blue))
}
}
}
}
.task {
await withErrorReporting {
try await syncEngine.fetchChanges()
}
}
}
}
}
@available(iOS 17, macOS 14, tvOS 17, *)
private struct CloudSharingViewRepresentable: UIViewControllerRepresentable {
let sharedRecord: SharedRecord
let availablePermissions: UICloudSharingController.PermissionOptions
let didFinish: (Result<Void, Error>) -> Void
let didStopSharing: () -> Void
let syncEngine: SyncEngine
public init(
sharedRecord: SharedRecord,
availablePermissions: UICloudSharingController.PermissionOptions = [],
didFinish: @escaping (Result<Void, Error>) -> Void = { _ in },
didStopSharing: @escaping () -> Void = {},
syncEngine: SyncEngine = {
@Dependency(\.defaultSyncEngine) var defaultSyncEngine
return defaultSyncEngine
}()
) {
self.sharedRecord = sharedRecord
self.didFinish = didFinish
self.didStopSharing = didStopSharing
self.availablePermissions = availablePermissions
self.syncEngine = syncEngine
}
public func makeCoordinator() -> _CloudSharingDelegate {
_CloudSharingDelegate(
share: sharedRecord.share,
didFinish: didFinish,
didStopSharing: didStopSharing,
syncEngine: syncEngine
)
}
public func makeUIViewController(context: Context) -> UICloudSharingController {
let controller = UICloudSharingController(
share: sharedRecord.share,
container: sharedRecord.container.rawValue
)
controller.delegate = context.coordinator
controller.availablePermissions = availablePermissions
return controller
}
public func updateUIViewController(
_ uiViewController: UICloudSharingController,
context: Context
) {
}
}
@available(iOS 17, macOS 14, tvOS 17, *)
public final class _CloudSharingDelegate: NSObject, UICloudSharingControllerDelegate {
let share: CKShare
let didFinish: (Result<Void, Error>) -> Void
let didStopSharing: () -> Void
let syncEngine: SyncEngine
init(
share: CKShare,
didFinish: @escaping (Result<Void, Error>) -> Void,
didStopSharing: @escaping () -> Void,
syncEngine: SyncEngine
) {
self.share = share
self.didFinish = didFinish
self.didStopSharing = didStopSharing
self.syncEngine = syncEngine
}
public func itemThumbnailData(for csc: UICloudSharingController) -> Data? {
share[CKShare.SystemFieldKey.thumbnailImageData] as? Data
}
public func itemTitle(for csc: UICloudSharingController) -> String? {
share[CKShare.SystemFieldKey.title] as? String
}
public func cloudSharingControllerDidSaveShare(_ csc: UICloudSharingController) {
didFinish(.success(()))
}
public func cloudSharingControllerDidStopSharing(_ csc: UICloudSharingController) {
Task {
await withErrorReporting(.sqliteDataCloudKitFailure) {
try await syncEngine.deleteShare(shareRecordID: share.recordID)
}
}
didStopSharing()
}
public func cloudSharingController(
_ csc: UICloudSharingController,
failedToSaveShareWithError error: any Error
) {
didFinish(.failure(error))
}
}
#endif
#endif