将Firebase快照阵列保存到NSUserDefaults

时间:2018-11-22 18:47:20

标签: swift firebase firebase-realtime-database nsuserdefaults

我正在使用Swift从我的Firebase数据库中检索数据。用户首次登录时,我想将Firebase快照中的“位置”另存为UserDefault。

static func getAllPlaces(){

    databaseRef = Database.database().reference()

    databaseRef.database.reference().child("places").observe(.childAdded) { (snapshot: DataSnapshot) in

        if let value = snapshot.value as? NSDictionary {

            let place = Place()

            let id = value["id"] as? String ?? "ID not found"
            let title = value["title"] as? String ?? "Title not found"
            let type = value["type"] as? String ?? ""

            place.id = id
            place.title = title
            place.type = type

            DispatchQueue.global().async {
                // Something here to append place data to UserDefaults?
                places.append(place) // appends to NSObject for later use
            }
        }

    }
}

当前代码可以正常工作-我只需要添加一些东西来存储它,以便稍后使用。

奖金问题:我在Firebase数据库中存储了几百个快照。我想将它们存储在设备上的原因是使用户不必继续下载数据。这是一个好主意吗?会占用很多内存吗?

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:4)

将自定义类/数据保存到UserDefaults的一种方法是对它们进行如下编码:

let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: place)
UserDefaults.standard.set(encodedData, forKey: "place")
UserDefaults.standard.synchronize()

然后您可以像这样解码它:

if UserDefaults.standard.object(forKey: "place") != nil{
    let decodedData = UserDefaults.standard.object(forKey: "place") as! Data
    let decodedPlace = NSKeyedUnarchiver.unarchiveObject(with: decodedData) as! Place
}

已针对Swift 4和iOS 12更新:

do {
    let encodedData: Data = try NSKeyedArchiver.archivedData(withRootObject: place, requiringSecureCoding: false)
    UserDefaults.standard.set(encodedData, forKey: "place")
    UserDefaults.standard.synchronize()
} catch {
        //Handle Error
}

do {
    if UserDefaults.standard.object(forKey: "place") != nil{
        let decodedData = UserDefaults.standard.object(forKey: "place") as! Data
        if let decodedPlace = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(decodedData) as? Place {
             //Do Something with decodedPlace
        }
    }
}
catch {
        //Handle Error
}