完成/线程订单协助
Posted
技术标签:
【中文标题】完成/线程订单协助【英文标题】:Completion/Threading order assistance 【发布时间】:2020-04-08 20:26:51 【问题描述】:我搞乱了我的完成处理程序的顺序,可能还有我的线程。我使用打印语句和计时器来检查我的工作,这是我发现的:
-
Time Lapsed 为 0.00076 秒,这显然不是预期的行为。
第 4 步立即显示,这又不是预期的行为。
显示第 1 步
第 2 步的显示时间为 2.92 秒,这很好。
唯一需要解决的问题是将第 4 步放在最后,因为这意味着第 1 步和第 2 步已完成。
这个函数在A类中:
static func loadDataAndSignIn(completion: @escaping () -> () )
let start = Date()
Auth.auth().signInAnonymously (result, error) in
if result != nil
print("Step 1 -> Signed In. UserId is: \(result?.user.uid)")
Variables.getDataFromFirestore
let end = Date()
print("Step 2 - > Data Fetched")
print("Data Fetched in \(end.timeIntervalSince(start)) seconds")
else
print(error?.localizedDescription ?? print("Sign in Error"))
DispatchQueue.main.async
completion()
print("Step 4 -> Signed In and Data Loaded")
这个函数也在A类中:
static func getDataFromFirestore(completion: (() -> Void)? = nil)
let db = Firestore.firestore()
db.collection("Offences").getDocuments (snapshot, error) in
if let error = error
print("Error getting documents: \(error.localizedDescription)")
else
Variables.offencesArray.removeAll()
for offence in snapshot!.documents
let offenceName = offence.get("name") as! String
let offencePoints = offence.get("points") as! Int
let offenceCost = offence.get("cost") as! Int
let offenceSection = offence.get("section") as! String
let offenceCategory = offence.get("category") as! String
let offenceObject = Offence(section: offenceSection, name: offenceName, cost: offenceCost, points: offencePoints, category: offenceCategory)
Variables.offencesArray.append(offenceObject)
DispatchQueue.main.async
completion?()
这是在 B 类的 viewDidLoad 中:
let start = Date()
Variables.loadDataAndSignIn
self.removeLoadingScreen()
let end = Date()
print("Time lapsed: \(end.timeIntervalSince(start))")
需要帮助我的线程/完成块按顺序恢复。
【问题讨论】:
【参考方案1】:在getDataFromFirestore
的完成处理程序中调用completion
,它在signInAnonymously
的完成处理程序中:
static func loadDataAndSignIn(completion: @escaping () -> () )
Auth.auth().signInAnonymously (result, error) in
if result != nil
print("Step 1 -> Signed In. UserId is: \(result?.user.uid)")
Variables.getDataFromFirestore
let end = Date()
print("Step 2 - > Data Fetched")
print("Data Fetched in \(end.timeIntervalSince(start)) seconds")
DispatchQueue.main.async
completion()
print("Step 4 -> Signed In and Data Loaded")
else
print(error?.localizedDescription ?? "Sign in Error")
注意:如果对 signInAnonymously
的调用中的 result
为 nil,您可能还想调用完成,例如:
[...]
else
print(error?.localizedDescription ?? "Sign in Error")
DispatchQueue.main.async
completion()
【讨论】:
以上是关于完成/线程订单协助的主要内容,如果未能解决你的问题,请参考以下文章
jmeter 发送http请求,并把获取到的请求的订单信息保存到文件中(转)
jmeter 发送http请求,并把获取到的请求的订单信息保存到文件中