-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathFire.swift
More file actions
476 lines (426 loc) · 15 KB
/
Fire.swift
File metadata and controls
476 lines (426 loc) · 15 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
// Fire.swift
// Created by Robby on 8/6/16.
// Copyright © 2016 Robby. All rights reserved.
/////////////////////////////////////////////////////////////////////////
// THREE PARTS: DATABASE, USER, STORAGE
// DATABASE:
// guards for setting and retrieving data
// handling all types of JSON data: nil, bool, int, float, string, array, dictionary
// Firebase uses Arrays which takes some extra safeguarding to manage
//
// getData() get data from database
// setData() overwrite data at a certain location in the database
// addData() generate a new key and add data as a child
// doesDataExist() check if data exists at a certain location
// USER:
// Firebase comes with FireAuth with a "user" class, but you can't edit it.
// solution: "users" entry in database with copies of User entries but with more info
// - each user is stored under their user.uid
// - can add as many fields as you want (nickname, photo, etc..)
// all the references to "user" are to our database's user entries, not the proper FIRAuth entry
//
//
// getCurrentUser() get all your profile information
// updateCurrentUserWith() update your profile with new information
// newUser() create a new entry for a user (usually for yourself after 1st login)
// userExists() check if a user exists
// STORAGE:
// firebase storage doesn't let you ask for the contents of its folder
// 1) everytime you save an image, it creates an entry for it in your database
// now you are manually maintaining a list of the contents of your firebase storage
// (unless you upload by some other means)
//
// 2) this class also maintains a cache of already-loaded images
import Firebase
enum JSONDataType {
case isBool, isInt, isFloat, isString, isArray, isDictionary, isURL, isNULL
// isURL is a special kind of string, kind of weird design i know, but it ends up being helpful
}
let STORAGE_IMAGE_DIR:String = "images/"
let STORAGE_DOCUMENT_DIR:String = "documents/"
enum StorageFileType : String{
case JPG, PNG, PDF
}
struct StorageFileMetadata {
var filename:String
var fullpath:String
var directory:String
var contentType:String
var type:StorageFileType
var size:Int
var url:URL?
var description:String?
}
// getting an image requires restriction on anticipated image file size
let IMG_SIZE_MAX:Int64 = 15 // megabytes
class Fire {
static let shared = Fire()
let database: DatabaseReference = Database.database().reference()
let storage = Storage.storage().reference()
// can monitor, pause, resume the current upload task
var currentUpload:StorageUploadTask?
var myUID:String? // if you are logged in, if not, == nil
fileprivate init() {
// setup USER listener
Auth.auth().addStateDidChangeListener { auth, listenerUser in
if let user = listenerUser {
print("SIGN IN: \(user.email ?? user.uid)")
self.myUID = user.uid
self.userExists(user, completionHandler: { (exists) in
if(!exists){
self.newUser(user, completionHandler: nil)
}
})
} else {
self.myUID = nil
print("SIGN OUT: no user")
}
}
let connectedRef = Database.database().reference(withPath: ".info/connected")
connectedRef.observe(.value, with: { snapshot in
if let connected = snapshot.value as? Bool , connected {
// internet connected
// banner alert
} else {
// internet disconnected
// banner alert
}
})
}
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
//
// DATABASE
// childURL = nil returns the root of the database
// childURL can contain multiple subdirectories separated with a slash: "one/two/three"
func getData(_ childURL:String?, completionHandler: @escaping (Any?) -> ()) {
var reference = self.database
if let url = childURL{
reference = self.database.child(url)
}
reference.observeSingleEvent(of: .value) { (snapshot: DataSnapshot) in
completionHandler(snapshot.value)
}
}
// add an object to the database at a childURL, function returns the auto-generated key to that object
func setData(_ object:Any, at path:String, completionHandler: ((Bool, DatabaseReference) -> ())?) {
self.database.child(path).setValue(object) { (error, ref) in
if let e = error{
print(e.localizedDescription)
if let completion = completionHandler{
completion(false, ref)
}
} else{
if let completion = completionHandler{
completion(true, ref)
}
}
}
}
// add an object AS A CHILD to the path, returns the key to that object
// ONLY if the object at path is a dictionary or array
// if it is a leaf (String, Number, Bool) it doesn't do anything (prevents overwriting)
func addData(_ object:Any, asChildAt path:String, completionHandler: ((_ success:Bool, _ newKey:String?, DatabaseReference?) -> ())?) {
self.doesDataExist(at: path) { (exists, dataType, data) in
switch dataType{
// 1) if array, it MAINTAINS the array structure (number key, not dictionary string key)
case .isArray:
let dbArray = data as! NSMutableArray
dbArray.add(object)
self.database.child(path).setValue(dbArray) { (error, ref) in
if let e = error{
print(e.localizedDescription)
if let completion = completionHandler{
completion(false, nil, nil)
}
} else{
if let completion = completionHandler{
completion(true, String(describing:dbArray.count-1), ref)
}
}
}
// 2) if dictionary, or doesn't exist, makes a new string key like usual
case .isDictionary, .isNULL:
self.database.child(path).childByAutoId().setValue(object) { (error, ref) in
if let e = error{
print(e.localizedDescription)
if let completion = completionHandler{
completion(false, nil, nil)
}
} else{
if let completion = completionHandler{
completion(true, ref.key, ref)
}
}
}
// 3) if object at path is a String or Int etc..(leaf node), return without doing anything
default:
if let completion = completionHandler{
completion(false, nil, nil);
}
}
}
}
func doesDataExist(at path:String, completionHandler: @escaping (_ doesExist:Bool, _ dataType:JSONDataType, _ data:Any?) -> ()) {
database.child(path).observeSingleEvent(of: .value) { (snapshot: DataSnapshot) in
if let data = snapshot.value{
completionHandler(true, self.typeOf(FirebaseData: data), data)
} else{
completionHandler(false, .isNULL, nil)
}
}
}
func typeOf(FirebaseData object:Any) -> JSONDataType {
if object is NSNumber{
let nsnum = object as! NSNumber
let boolID = CFBooleanGetTypeID() // the type ID of CFBoolean
let numID = CFGetTypeID(nsnum) // the type ID of num
if numID == boolID{
return .isBool
}
if nsnum.floatValue == Float(nsnum.intValue){
return .isInt
}
return .isFloat
} else if object is String {
if let url: URL = URL(string: object as! String) {
if UIApplication.shared.canOpenURL(url){
return .isURL
} else{
return .isString
}
} else{
return .isString
}
} else if object is NSArray || object is NSMutableArray{
return .isArray
} else if object is NSDictionary || object is NSMutableDictionary{
return .isDictionary
}
return .isNULL
}
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
//
// USER
func getCurrentUser(_ completionHandler: @escaping (String, [String:Any]) -> ()) {
guard let user = Auth.auth().currentUser else{
return
}
database.child("users").child(user.uid).observeSingleEvent(of: .value) { (snapshot: DataSnapshot) in
if let userData = snapshot.value as? [String:Any]{
completionHandler(user.uid, userData)
} else{
print("user has no data")
}
}
}
func getUser(UID:String, _ completionHandler: @escaping ([String:Any]) -> ()){
database.child("users").child(UID).observeSingleEvent(of: .value, with: { (snapshot) in
if let userData = snapshot.value as? [String:Any]{
completionHandler(userData)
}
})
}
func updateCurrentUserWith(key:String, object value:Any, completionHandler: ((_ success:Bool) -> ())? ) {
guard let user = Auth.auth().currentUser else{
if let completion = completionHandler{
completion(false)
}
return
}
database.child("users").child(user.uid).updateChildValues([key:value]) { (error, ref) in
if let e = error{
print(e.localizedDescription)
if let completion = completionHandler{
completion(false)
}
} else{
// print("saving \(value) into \(key)")
if let completion = completionHandler{
completion(true)
}
}
}
}
func newUser(_ user:User, completionHandler: ((_ success:Bool) -> ())? ) {
var newUser:[String:Any] = [
"createdAt": Date.init().timeIntervalSince1970
]
// copy user data over from AUTH
if let nameString = user.displayName { newUser["name"] = nameString }
if let imageURL = user.photoURL { newUser["image"] = imageURL }
if let emailString = user.email { newUser["email"] = emailString }
database.child("users").child(user.uid).updateChildValues(newUser) { (error, ref) in
if let e = error{
print(e.localizedDescription)
if let completion = completionHandler{
completion(false)
}
} else{
if let completion = completionHandler{
completion(true)
}
}
}
}
func userExists(_ user: User, completionHandler: @escaping (Bool) -> ()) {
database.child("users").child(user.uid).observeSingleEvent(of: .value) { (snapshot: DataSnapshot) in
if snapshot.value != nil{
completionHandler(true)
} else{
completionHandler(false)
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
//
// STORAGE
// Key is filename in the images/ folder in the Firebase storage bucket
// example: "0C5BABB0D5CA.jpg"
var fileCache:[String:Data] = [:]
func imageFromStorageBucket(_ filename: String, completionHandler: @escaping (_ image:UIImage, _ didRequireDownload:Bool) -> ()) {
if let imageData = fileCache[filename]{
if let image = UIImage(data: imageData){
//TODO: check timestamp against database, force a data refresh
completionHandler(image, false)
return
}
}
let storage = Storage.storage().reference()
let imageRef = storage.child(STORAGE_IMAGE_DIR + filename)
imageRef.getData(maxSize: IMG_SIZE_MAX * 1024 * 1024) { (data, error) in
if let e = error{
print(e.localizedDescription)
} else{
if let imageData = data {
if let image = UIImage(data: imageData){
self.fileCache[filename] = imageData
completionHandler(image, true)
} else{
print("problem making image out of received data")
}
}
}
}
}
// specify a UUIDFilename, or it will generate one for you
func uploadFileAndMakeRecord(_ data:Data, fileType:StorageFileType, description:String?, completionHandler: @escaping (_ metadata:StorageFileMetadata) -> ()) {
// prep file info
var filename:String = UUID.init().uuidString
var storageDir:String
let uploadMetadata = StorageMetadata()
switch fileType {
case .JPG:
filename = filename + ".jpg"
storageDir = STORAGE_IMAGE_DIR
uploadMetadata.contentType = "image/jpeg"
case .PNG:
filename = filename + ".png"
storageDir = STORAGE_IMAGE_DIR
uploadMetadata.contentType = "image/png"
case .PDF:
filename = filename + ".pdf"
storageDir = STORAGE_DOCUMENT_DIR
uploadMetadata.contentType = "application/pdf"
}
let filenameAndPath:String = storageDir + filename
// STEP 1 - upload file to storage
// TODO: make currentUpload an array, if upload in progress add this to array
currentUpload = storage.child(filenameAndPath).putData(data, metadata: uploadMetadata, completion: { (metadata, error) in
if let e = error {
print(e.localizedDescription)
} else {
// upload success, add file to cache
self.fileCache[filename] = data
if let meta = metadata{
// STEP 2 - record new file in database
var entry:[String:Any] = ["filename":filename,
"fullpath":filenameAndPath,
"directory":storageDir,
"content-type":uploadMetadata.contentType ?? "",
"type":fileType.rawValue,
"size":data.count]
if let downloadURL = meta.downloadURL(){
entry["url"] = downloadURL.absoluteString
}
if let descriptionString = description{
entry["description"] = descriptionString
}
let key = self.database.child("files/" + storageDir).childByAutoId().key
self.database.child("files/" + storageDir).updateChildValues([key:entry]) { (error, ref) in
let info:StorageFileMetadata = StorageFileMetadata(filename: filename, fullpath: filenameAndPath, directory: storageDir, contentType: uploadMetadata.contentType ?? "", type: fileType, size: data.count, url: meta.downloadURL(), description: description)
completionHandler(info)
}
}
}
})
}
}
extension UIImageView {
public func imageFromStorage(_ filename: String){
// filename:String is the filename in the Firebase Storage bucket, no directories
// example: "0C5BABB0D5CA.jpg"
if let imageData = Fire.shared.fileCache[filename]{
if let image = UIImage(data: imageData){
self.image = image
return
}
}
let storage = Storage.storage().reference()
let imageRef = storage.child("images/" + filename)
imageRef.getData(maxSize: IMG_SIZE_MAX * 1024 * 1024) { (data, error) in
if let e = error{
print(e.localizedDescription)
} else{
if let imageData = data {
if let image = UIImage(data: imageData){
Fire.shared.fileCache[filename] = imageData
self.image = image
}
}
}
}
}
public func profileImageForUser(uid: String){
Fire.shared.getUser(UID: uid) { (userData) in
if let imageFilename = userData["image"] as? String{
if let imageData = Fire.shared.fileCache[imageFilename]{
if let image = UIImage(data: imageData){
self.image = image
return
}
}
let storage = Storage.storage().reference()
let imageRef = storage.child("images/" + imageFilename)
imageRef.getData(maxSize: IMG_SIZE_MAX * 1024 * 1024) { (data, error) in
if let e = error{
print(e.localizedDescription)
} else{
if let imageData = data {
if let image = UIImage(data: imageData){
Fire.shared.fileCache[imageFilename] = imageData
self.image = image
}
}
}
}
}
}
}
public func imageFromUrl(_ urlString: String) {
if let url = URL(string: urlString) {
let request:URLRequest = URLRequest(url: url)
let session:URLSession = URLSession.shared
let task = session.dataTask(with: request, completionHandler: {data, response, error -> Void in
DispatchQueue.main.async {
if let imageData = data as Data? {
self.image = UIImage(data: imageData)
}
}
})
task.resume()
}
}
}