gpt4 book ai didi

iphone - 检索设备设置后更新 UI

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

我想在 Swift 中做一些简单的事情。我必须从设备中检索一些设置,然后使用这些设置初始化一些 UI 控件。完成检索可能需要几秒钟,所以我不希望代码在检索(异步)之前继续。

我已经阅读了许多网站上的无数帖子,包括这个,也阅读了很多教程。似乎没有一个适合我。

此外,为了封装,我想将细节保留在设备对象中。

当我运行应用程序时,我先看到初始化方法的打印,然后再看到初始化方法的打印。

// 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!

最佳答案

如果你打算用你自己的函数包装一个异步函数,通常最好也给你的包装函数一个完成处理程序。注意对完成处理程序的调用。这是您传递结果值的地方(即在闭包内):

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

请始终记住,代码将在异步函数完成之前流过。因此,您必须构建代码,以便任何依赖于返回值或错误的内容都不会在完成之前执行。

关于iphone - 检索设备设置后更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50335941/

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