我想在Swift中做一些简单的事情。我必须从设备中检索一些设置,然后使用这些设置初始化一些UI控件。可能需要几秒钟才能完成检索,所以我不希望代码在检索(异步)之后才继续。
我已经在许多网站上阅读了无数的帖子,包括这个网站,并阅读了许多教程。似乎没有一个对我有效。
另外,为了便于封装,我希望将详细信息保存在device对象中。
当我运行应用程序时,在我看到来自初始化方法的打印之前,我看到了来自该方法的打印。
// Initializing method
brightnessLevel = 100
device.WhatIsTheBrightnessLevel(level: &brightnessLevel)
print("The brightness level is \(brightnessLevel)")
// method with the data retrieval code
func WhatIsTheBrightnessLevel(level brightness: inout Int) -> CResults
{
var brightness: Int
var characteristic: HMCharacteristic
var name: String
var results: CResults
var timeout: DispatchTime
var timeoutResult: DispatchTimeoutResult
// Refresh the value by querying the lightbulb
name = m_lightBulbName
characteristic = m_brightnessCharacteristic!
brightness = 100
timeout = DispatchTime.now() + .seconds(CLightBulb.READ_VALUE_TIMEOUT)
timeoutResult = .success
results = CResults()
results.SetResult(code: CResults.code.success)
let dispatchGroup = DispatchGroup()
DispatchQueue.global(qos: .userInteractive).async
{
//let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
characteristic.readValue(completionHandler:
{ (error) in
if error != nil
{
results.SetResult(code: CResults.code.homeKitError)
results.SetHomeKitDescription(text: error!.localizedDescription)
print("Error in reading the brightness level for \(name): \(error!.localizedDescription)")
}
else
{
brightness = characteristic.value as! Int
print("CLightBulb: -->Read the brightness level. It is \(brightness) at " + Date().description(with: Locale.current))
}
dispatchGroup.leave()
})
timeoutResult = dispatchGroup.wait(timeout: timeout)
if (timeoutResult == .timedOut)
{
results.SetResult(code: CResults.code.timedOut)
}
else
{
print("CLightBulb: (After wait) The brightness level is \(brightness) at " + Date().description(with: Locale.current))
self.m_brightnessLevel = brightness
}
}
return(results)
}
Thank you!发布于 2018-05-16 23:30:22
如果你打算用你自己的函数包装一个异步函数,通常最好也给你的包装器函数一个完成处理程序。请注意对完成处理程序的调用。这就是你传递结果值的地方(即在闭包中):
func getBrightness(characteristic: HMCharacteristic, completion: @escaping (Int?, Error?) -> Void) {
characteristic.readValue { (error) in
//Program flows here second
if error == nil {
completion(characteristic.value as? Int, nil)
} else {
completion(nil, error)
}
}
//Program flows here first
}然后,当你调用你的函数时,你只需要确保你是在完成处理程序中处理结果(即闭包):
getBrightness(characteristic: characteristic) { (value, error) in
//Program flows here second
if error == nil {
if let value = value {
print(value)
}
} else {
print("an error occurred: \(error.debugDescription)")
}
}
//Program flows here first请始终记住,在异步函数完成之前,代码将流经。所以你必须组织你的代码,使任何依赖于返回的值或错误的东西在完成之前都不会被执行。
https://stackoverflow.com/questions/50335941
复制相似问题