将Firebase中的数据保存到Swift中的全局变量中

时间:2018-02-11 17:18:03

标签: swift firebase asynchronous

我尝试将从Firebase检索到的数据保存到全局变量spendDict。但是,在我调用retrieveSpend()之后,在关闭之外,spendDict仍然是空的。如何将Firebase的最终结果保存到Swift中的全局变量中。感谢。

该功能如下所示:

   var spendDict: [String:[String]] = [:]

   override func viewDidLoad() {
            super.viewDidLoad()


            retrieveSpend()


        }

   func retrieveSpend(){
        // the dict will be [time:[amount , amount , amount]]
         var spendDict :[String: [String]] = [:]

         let spendDB = Database.database().reference().child("Spend")
         spendDB.observe(.childAdded, with:{(snapshot) in
            let returnValue = snapshot.value as! Dictionary<String, String>
            var amount_retrieved = returnValue["amount"]
            var time_retrieved = returnValue["time"]
            var tag_retrieved = returnValue["tag"]

            if self.spendDict.index(forKey: time_retrieved!) == nil {
                // the key does not exist in the dictionary

                self.spendDict[time_retrieved!] = [amount_retrieved!]
            }
            else{


            self.spendDict[time_retrieved!]?.append(amount_retrieved!)
            }
            print("spendDict in closure ", spendDict)

        })
        print("spendDict outside the closure " , spendDict)



    }

这是输出:

spendDict outside the closure  [:]
spendDict in closure  ["02-07-2018": ["7"]]
spendDict in closure  ["02-07-2018": ["7"], "02-06-2018": ["6"]]
spendDict in closure  ["02-05-2018": ["5"], "02-07-2018": ["7"], "02-06-2018": ["6"]]
spendDict in closure  ["02-06-2018": ["6"], "02-08-2018": ["8"], "02-05-2018": ["5"], "02-07-2018": ["7"]]
spendDict in closure  ["02-06-2018": ["6"], "02-08-2018": ["8"], "02-05-2018": ["5"], "02-07-2018": ["7"], "02-09-2018": ["9"]]
spendDict in closure  ["02-01-2018": ["1"], "02-06-2018": ["6"], "02-08-2018": ["8"], "02-05-2018": ["5"], "02-07-2018": ["7"], "02-09-2018": ["9"]]
spendDict in closure  ["02-09-2018": ["9"], "02-06-2018": ["6"], "02-02-2018": ["2"], "02-08-2018": ["8"], "02-01-2018": ["1"], "02-05-2018": ["5"], "02-07-2018": ["7"]]
spendDict in closure  ["02-09-2018": ["9"], "02-03-2018": ["3"], "02-06-2018": ["6"], "02-02-2018": ["2"], "02-08-2018": ["8"], "02-01-2018": ["1"], "02-05-2018": ["5"], "02-07-2018": ["7"]]
spendDict in closure  ["02-09-2018": ["9"], "02-03-2018": ["3"], "02-06-2018": ["6"], "02-02-2018": ["2"], "02-08-2018": ["8", "88"], "02-01-2018": ["1"], "02-05-2018": ["5"], "02-07-2018": ["7"]]
spendDict in closure  ["02-09-2018": ["9"], "02-03-2018": ["3"], "02-06-2018": ["6"], "02-02-2018": ["2"], "02-10-2018": ["10"], "02-08-2018": ["8", "88"], "02-01-2018": ["1"], "02-05-2018": ["5"], "02-07-2018": ["7"]]

0 个答案:

没有答案