自定义Firebase数据服务类:Swift 3 [英] Custom Firebase Data Service Class : Swift 3

查看:204
本文介绍了自定义Firebase数据服务类:Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种干净的方式来从Swift中检索(有时保存)来自Firebase的数据。我讨厌所有的数据库调用都写在视图控制器代码的中间。所以我正在寻找一些自定义的数据服务类。我发现这个教程是接近我想要的: http://www.mobilecyberpunks.com/?p= 82个。他们答应了第二部分,但是我找不到第二部分,所以我猜这是从来没有做过的。在第二部分中,他们承诺将使用此自定义数据服务(这是整个事件中最重要的部分)来检索和保存数据。

我正在考虑一个API类(如本教程中所述),当我检索数据并完成从firebase的检索时,我将其保存在数据中设置在这个API类。然后我会通知通知中心。但我不确定这是最好的做法还是一个很好的方法来做到这一点。

有没有人知道如何做到这一点(完成本教程我发现或以另一种方式)?

在此先感谢!

解决方案

开始使用这个解决方案,并打磨了一下,我来到了一个非常方便的解决方案。



我创建了一个名为FirebaseAPI的自定义类。这是一个单身人士课程。这个类包含Firebase的所有方法(认证,数据库,存储,...)。
$ b

例子:

< FirebaseAPI.swift

 导入FirebaseAuth 
导入FirebaseDatabase

class FirebaseAPI {
static let shared = FirebaseAPI()

private init(){}

//认证
func logInUser(onCompletion:如果错误== nil {
onCompletion(user!),那么
中的{(user,error) .uid)
} else {
onCompletion(nil)
}
})
}

//数据库
func getObjects(参数:ParamaterClass,onCompletion:@escaping([ObjectClass]) - > Void){
Constants.Firebase.References.Object?.observe(.value,with:{snapshot in
var objects = [ObjectClass]()

如果snapshot.exists(){
为snapshot.children.allObjects中的子元素{
let object = Object(snapshot:child as! FIRDataSnapshot)
objects.append(object)
}
}
onCompletion(objects)
})
}
}

Constants.swift

 导入FirebaseDatabase 

结构常量{
结构Firebase {
static var CurrentUser:FIRDatabaseReference?
static var对象:FIRDatabaseReference?
}
}

AppDelegate.swift

 导入UIKit 
导入Firebase

@UIApplicationMain $ b $ class AppDelegate:UIResponder, UIApplicationDelegate {
var window:UIWindow?

func application(_ application:UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplicationLaunchOptionsKey:Any]?) - > Bool {
FIRApp.configure()

FirebaseAPI.shared.logInUser(onCompletion {uid in
if uid!= nil {
Constants.Firebase.References.CurrentUser = FIRDatabase.database()。reference()。child(users)。child(uid!)
Constants.Firebase.References.CurrentUser.keepSynced(true)

Constants.Firebase .References.Objects = FIRDatabase.database()。reference()。child(objects)
Constants.Firebase.Reference.Objects?.keepSynced(true)
}
})
}
return true
}

我可以举个例子在ViewController的FirebaseAPI中调用方法,但在这里的AppDelegate.swift的代码(FirebaseAPI.shared.logInUser方法)中给出了一个这样的方法的示例。



到目前为止,在3个不同的项目中使用了这个结构,它可以很流畅地运行!


I'm searching for a clean way to retrieve (and sometimes save) data from Firebase in Swift. It's annoying me that all my database calls are written in the middle of the view controller code. So I'm looking for some kind of custom data service class. I found this tutorial that's close to what I want: http://www.mobilecyberpunks.com/?p=82.

They promised a Part II but I cannot find this second part, so I guess this was never made. In this second part they promised to cover retrieving and saving data with this custom data service (which is the most important part of the whole thing for me).

I'm thinking of an API class (like in the tutorial) and when I'm retrieving data, and it finishes retrieving from firebase, I save it in a data set in this api class. Then I will posting a notification with Notification Center. But I'm am not sure whether this is best practice or a good way to do this.

Has anyone an idea how to do this (finishing this tutorial I found or in another way)?

Thanks in advance!

解决方案

I started to use this solution and polished it a little bit, and I came to a pretty handy solution.

I created a custom class named FirebaseAPI. This is a singleton class. This class contains all the methods for Firebase (Authentication, Database, Storage, ...).

Example:

FirebaseAPI.swift

import FirebaseAuth
import FirebaseDatabase 

class FirebaseAPI {
    static let shared = FirebaseAPI()

    private init() {}

    //Authentication
    func logInUser(onCompletion: @escaping (String?) -> Void {
        FIRAuth.auth().signInAnonymously(completion: {(user, error) in 
            if error == nil {
                onCompletion(user!.uid)
            } else {
                onCompletion(nil)
            }
        })
    }

    //Database
    func getObjects(parameter: ParamaterClass, onCompletion: @escaping ([ObjectClass]) -> Void) {
        Constants.Firebase.References.Object?.observe(.value, with: { snapshot in
            var objects = [ObjectClass]()

            if snapshot.exists() {
                for child in snapshot.children.allObjects {
                    let object = Object(snapshot: child as! FIRDataSnapshot)
                    objects.append(object)
                }
            }
            onCompletion(objects)
        })
    }
}

Constants.swift

import FirebaseDatabase 

struct Constants {
    struct Firebase {
        static var CurrentUser: FIRDatabaseReference?
        static var Objects: FIRDatabaseReference?
    }
}

AppDelegate.swift

import UIKit
import Firebase 

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        FIRApp.configure()

        FirebaseAPI.shared.logInUser(onCompletion { uid in 
            if uid != nil {
                Constants.Firebase.References.CurrentUser = FIRDatabase.database().reference().child("users").child(uid!)
                Constants.Firebase.References.CurrentUser.keepSynced(true)

               Constants.Firebase.References.Objects = FIRDatabase.database().reference().child("objects")
               Constants.Firebase.Reference.Objects?.keepSynced(true)
            }
        })
    }
    return true
}

I can give you a example of calling methods in the FirebaseAPI in a ViewController, but an example of such a method is given in the code of the AppDelegate.swift up here (the FirebaseAPI.shared.logInUser method).

Used this structure in 3 different projects up till now and it works fluently!

这篇关于自定义Firebase数据服务类:Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆