forked from parse-community/Parse-Swift
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Contents.swift
381 lines (331 loc) · 11.4 KB
/
Contents.swift
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
//: [Previous](@previous)
//: For this page, make sure your build target is set to ParseSwift and targeting
//: `My Mac` or whatever the name of your mac is. Also be sure your `Playground Settings`
//: in the `File Inspector` is `Platform = macOS`. This is because
//: Keychain in iOS Playgrounds behaves differently. Every page in Playgrounds should
//: be set to build for `macOS` unless specified.
import PlaygroundSupport
import Foundation
import ParseSwift
PlaygroundPage.current.needsIndefiniteExecution = true
Task {
do {
try await initializeParse()
} catch {
assertionFailure("Error initializing Parse-Swift: \(error)")
}
}
//: Create your own value typed `ParseObject`.
struct GameScore: ParseObject {
//: These are required by ParseObject.
var objectId: String?
var createdAt: Date?
var updatedAt: Date?
var ACL: ParseACL?
var originalData: Data?
//: Your own properties
var points: Int?
var location: ParseGeoPoint?
var fence: ParsePolygon?
/*:
Optional - implement your own version of merge
for faster decoding after updating your `ParseObject`.
*/
func merge(with object: Self) throws -> Self {
var updated = try mergeParse(with: object)
if updated.shouldRestoreKey(\.points,
original: object) {
updated.points = object.points
}
if updated.shouldRestoreKey(\.location,
original: object) {
updated.location = object.location
}
if updated.shouldRestoreKey(\.fence,
original: object) {
updated.fence = object.fence
}
return updated
}
}
//: It's recommended to place custom initializers in an extension
//: to preserve the memberwise initializer.
extension GameScore {
//: Custom initializer.
init(points: Int) {
self.points = points
}
}
//: Define initial GameScore.
var score = GameScore(points: 10)
do {
try score.location = ParseGeoPoint(latitude: 40.0, longitude: -30.0)
let points: [ParseGeoPoint] = [
try .init(latitude: 35.0, longitude: -30.0),
try .init(latitude: 42.0, longitude: -35.0),
try .init(latitude: 42.0, longitude: -20.0)
]
score.fence = try ParsePolygon(points)
}
/*:
Save asynchronously with completion block - performs work on background
queue and returns to specified callbackQueue.
If no callbackQueue is specified it returns to main queue.
*/
score.save { result in
switch result {
case .success(let savedScore):
assert(savedScore.objectId != nil)
assert(savedScore.createdAt != nil)
assert(savedScore.updatedAt != nil)
assert(savedScore.points == 10)
assert(savedScore.location != nil)
assert(savedScore.fence != nil)
guard let location = savedScore.location else {
print("Something went wrong")
return
}
print("Saved location: \(location)")
guard let fence = savedScore.fence else {
print("Something went wrong")
return
}
print("Saved polygon: \(fence)")
print("Saved polygon geopoints: \(fence.coordinates)")
case .failure(let error):
assertionFailure("Error saving: \(error)")
}
}
//: Now we will show how to query based on the `ParseGeoPoint`.
var query: Query<GameScore> //: Store query for later user
var constraints = [QueryConstraint]()
do {
let pointToFind = try ParseGeoPoint(latitude: 40.0, longitude: -30.0)
constraints.append(near(key: "location", geoPoint: pointToFind))
query = GameScore.query(constraints)
query.find { results in
switch results {
case .success(let scores):
assert(scores.count >= 1)
scores.forEach { (score) in
print("""
Someone with objectId \"\(score.objectId!)\"
has a points value of \"\(String(describing: score.points))\" near me
""")
}
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
}
/*:
If you only want to query for points in descending order, use the order enum.
Notice the "var", the query has to be mutable since it is a value type.
*/
var querySorted = query
querySorted.order([.descending("points")])
querySorted.find { results in
switch results {
case .success(let scores):
assert(scores.count >= 1)
scores.forEach { (score) in
print("""
Someone with objectId \"\(score.objectId!)\"
has a points value of \"\(String(describing: score.points))\" near me
""")
}
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
//: If you only want to query for points > 50, you can add more constraints.
constraints.append("points" > 9)
var query2 = GameScore.query(constraints)
query2.find { results in
switch results {
case .success(let scores):
assert(scores.count >= 1)
scores.forEach { (score) in
print("""
Someone with objectId \"\(score.objectId!)\" has a
points value of \"\(String(describing: score.points))\" near me which is greater than 9
""")
}
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
//: If you want to query for points > 50 and whose location is undefined.
var query3 = GameScore.query("points" > 50, doesNotExist(key: "location"))
query3.find { results in
switch results {
case .success(let scores):
scores.forEach { (score) in
print("""
Someone has a points value of \"\(String(describing: score.points))\"
with no geopoint \(String(describing: score.location))
""")
}
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
//: If you want to query for points > 50 and whose location is null or undefined.
var anotherQuery3 = GameScore.query("points" > 50, isNull(key: "location"))
anotherQuery3.find { results in
switch results {
case .success(let scores):
scores.forEach { (score) in
print("""
Someone has a points value of \"\(String(describing: score.points))\"
with no geopoint \(String(describing: score.location))
""")
}
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
//: If you want to query for points > 9 and whose location is not undefined.
var query4 = GameScore.query("points" > 9, exists(key: "location"))
query4.find { results in
switch results {
case .success(let scores):
assert(scores.count >= 1)
scores.forEach { (score) in
print("""
Someone has a points of \"\(String(describing: score.points))\"
with geopoint \(String(describing: score.location))
""")
}
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
//: If you want to query for points > 9 and whose location is not null or undefined.
var anotherQuery4 = GameScore.query("points" > 9, isNotNull(key: "location"))
anotherQuery4.find { results in
switch results {
case .success(let scores):
assert(scores.count >= 1)
scores.forEach { (score) in
print("""
Someone has a points of \"\(String(describing: score.points))\"
with geopoint \(String(describing: score.location))
""")
}
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
let query5 = GameScore.query("points" == 50)
let query6 = GameScore.query("points" == 200)
var query7 = GameScore.query(or(queries: [query5, query6]))
query7.find { results in
switch results {
case .success(let scores):
scores.forEach { (score) in
print("""
Someone has a points value of \"\(String(describing: score.points))\"
with geopoint using OR \(String(describing: score.location))
""")
}
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
//: Find all GameScores.
let query8 = GameScore.query
query8.findAll { result in
switch result {
case .success(let scores):
print(scores)
case .failure(let error):
print(error.localizedDescription)
}
}
do {
let points: [ParseGeoPoint] = [
try .init(latitude: 35.0, longitude: -30.0),
try .init(latitude: 42.0, longitude: -35.0),
try .init(latitude: 42.0, longitude: -20.0)
]
let query9 = GameScore.query(geoPoint("location", within: points))
query9.find { results in
switch results {
case .success(let scores):
scores.forEach { (score) in
print("""
Someone has a points value of \"\(String(describing: score.points))\"
with a geolocation \(String(describing: score.location)) within the
polygon using points: \(points)
""")
}
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
} catch {
print("Could not create geopoints: \(error)")
}
do {
let points: [ParseGeoPoint] = [
try .init(latitude: 35.0, longitude: -30.0),
try .init(latitude: 42.0, longitude: -35.0),
try .init(latitude: 42.0, longitude: -20.0)
]
let polygon = try ParsePolygon(points)
let query10 = GameScore.query(geoPoint("location", within: polygon))
query10.find { results in
switch results {
case .success(let scores):
scores.forEach { (score) in
print("""
Someone has a points value of \"\(String(describing: score.points))\"
with a geolocation \(String(describing: score.location)) within the
polygon: \(polygon)
""")
}
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
} catch {
print("Could not create geopoints: \(error)")
}
do {
let location = try ParseGeoPoint(latitude: 40.0, longitude: -30.0)
let query = GameScore.query(polygon("fence", contains: location))
query.find { results in
switch results {
case .success(let scores):
scores.forEach { (score) in
print("""
Someone has a points value of \"\(String(describing: score.points))\"
with a geolocation \(location) within the
polygon: \(String(describing: score.location))
""")
}
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
} catch {
print("Could not create geopoints: \(error)")
}
//: Hint of the previous query (asynchronous)
query2 = query2.hint("_id_")
query2.find { result in
switch result {
case .success(let scores):
print(scores)
case .failure(let error):
print(error.localizedDescription)
}
}
/*: Explain the previous query. Read the documentation note on `explain`
queries and use a type-erased wrapper such as AnyCodable.
*/
// let explain: AnyDecodable = try query8.firstExplain()
// print(explain)
PlaygroundPage.current.finishExecution()
//: [Next](@next)