gpt4 book ai didi

ios - 不确定如何在异步调用之外追加数组

转载 作者:行者123 更新时间:2023-11-28 06:06:39 25 4
gpt4 key购买 nike

我正在尝试使用 observeSingleEvent 从 Firebase 获取名为 City 的某些子节点,但我在尝试将其拉入主线程时遇到问题。我结合使用了完成处理程序和调度调用,但我不确定我做错了什么,除了在异步方面不是那么好。在 viewDidLoad 中,我试图从 setupSavedLocations 函数中附加我的 key 并将其返回到 savedLocations 我觉得我很接近。我错过了什么?

编辑:问题的清晰度

import UIKit
import Firebase

class SavedLocationsViewController: UIViewController {

var userID: String?
var savedLocations: [String] = []

override func viewDidLoad() {
super.viewDidLoad()

setupSavedLocations() { (savedData) in
DispatchQueue.main.async(execute: {
self.savedLocations = savedData
print("inside", self.savedLocations)
})
}
print("outside",savedLocations)
}

func setupSavedLocations(completion: @escaping ([String]) -> ()) {
guard let user = userID else { return }
let databaseRef = Database.database().reference(fromURL: "https://************/City")
var dataTest : [String] = []
databaseRef.observeSingleEvent(of: .value, with: {(snapshot) in
let childString = "Users/" + user + "/City"
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
dataTest.append(key)
}
completion(dataTest)
})
}

示例输出

outside []
inside ["New York City", "San Francisco"]

最佳答案

setupSavedLocations 的调用是异步的,运行时间比 cpu 完成 viewDidLoad 的时间长,这就是您的数据未显示的原因。您还可以从输出中注意到 outsideinside 之前被调用,这证明了这一点。处理这种情况的正确方法是向用户显示他们需要等待 IO 调用,然后在您拥有相关信息时向他们显示相关信息,如下所示。

class SavedLocationsViewController: UIViewController {

var myActivityIndicator: UIActivityIndicatorView?

override func viewDidLoad() {
super.viewDidLoad()

setupSavedLocations() { (savedData) in
DispatchQueue.main.async(execute: {
showSavedLocations(locations: savedData)
})
}
// We don't have any data here yet from the IO call
// so we show the user an indicator that the call is
// being made and they have to wait

let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
myActivityIndicator.center = view.center
myActivityIndicator.startAnimating()
self.view.addSubview(myActivityIndicator)
self.myActivityIndicator = myActivityIndicator
}

func showSavedLocations(locations: [String]) {
// This function has now been called and the data is passed in.
// Indicate to the user that the loading has finished by
// removing the activity indicator
myActivityIndicator?.stopAnimating()
myActivityIndicator?.removeFromSuperview()

// Now that we have the data you can do whatever you want with it here
print("Show updated locations: \(locations)")
}

关于ios - 不确定如何在异步调用之外追加数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47996168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com