gpt4 book ai didi

swift - 从 api 调用获取数据后无法更新实例变量

转载 作者:行者123 更新时间:2023-11-30 10:55:31 25 4
gpt4 key购买 nike

这是我的类中的实例变量
var 餐厅 = String;

    override func viewDidLoad() {
super.viewDidLoad()

self.pool = AWSCognitoIdentityUserPool(forKey: AWSCognitoUserPoolsSignInProviderKey)
if (self.user == nil) {
self.user = self.pool?.currentUser()
}
self.title = self.user?.username
// fills the list with a certain data set
//self.refresh()

这是我的完成 block

    grabData {
for values in self.restaurants{
print(values)
}
}


}

这是进行 api 调用的函数

func grabData(completion : @escaping() -> ()){

let databaseMap = AWSDynamoDBObjectMapper.default()
let expression = AWSDynamoDBScanExpression()


databaseMap.scan(Restaraunt.self, expression: expression,completionHandler:{(response:AWSDynamoDBPaginatedOutput?,error:Error?)-> Void in

// testing the response
if(response != nil){
print("got a reponse")
if(response?.items.count == 0)
{
print("did not get a response")
}else{


for item in (response?.items)!{

let data: Restaraunt = item as! Restaraunt;

let name: String = data._name as! String;
self.restaurants.append(name)
}

}
}
})

completion()
}

该函数似乎没有更新实例变量,我知道在设置一些断点后我得到了正确的数据。 (当我在 for 循环上设置断点时,它显示餐厅实例变量为空)。

最佳答案

您错误地调用了completion()。它在您实际获取数据之前被调用。您必须从完成处理程序中调用它:

databaseMap.scan(Restaraunt.self, expression: expression, completionHandler: { (response: AWSDynamoDBPaginatedOutput?, error: Error?) in

// testing the response
if (response != nil){
print("got a reponse")

if (response?.items.count == 0) {
print("did not get a response")
} else {
for item in (response?.items)! {
let data: Restaraunt = item as! Restaraunt;
let name: String = data._name as! String;
self.restaurants.append(name)
}
}
}

// this has to be inside the closure
completion()
})

关于swift - 从 api 调用获取数据后无法更新实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53990460/

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