gpt4 book ai didi

ios - 在 viewDidLoad 之前执行一个函数

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

此 View 将提出一组问题。这些问题将从 api 中读取。我有两种方法可以在最后一个 View 中加载它们,或者在当前 View 中但在 viewDidLoad 方法之前加载它们。我尝试了 viewWillAppear 但效果不佳。我该怎么做?

编辑:

这是从 api 读取数据的函数:

func readData(id: String, userCompletionHandler: @escaping ([String], Error?) -> Void){
let request = NSMutableURLRequest(url: NSURL(string: "http://adminsapi.somee.com/Api/Test/?id=\(id)")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
request.httpMethod = "GET"

var questionArr = [String]()
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
if response != nil {
//print("Response: \(response!)")
}
if let data = data {
do{
self.questionObject = try JSONDecoder().decode([Questions].self, from: data)
for question in self.questionObject{
questionArr.append(question.question)
}
userCompletionHandler(questionArr, nil)
} catch{
print("Error in retrieving data: \(error)")
}
}
else{
print("Error: \(String(describing: error))")
}
})
dataTask.resume()
}

这是我导航到下一个 View Controller 的地方:

func moveToNextVC(finalString: String){
let VC1 = self.storyboard?.instantiateViewController(withIdentifier: "QuestionsTableViewController") as? QuestionsTableViewController
if finalString.lowercased().contains("abdominal distention"){
readData(id: "1", userCompletionHandler: { data, error in
VC1?.questions = data
})
self.present(VC1!, animated: true, completion: nil)
}
}

The problem is when I print the questions array in "QuestionsTableViewController" it is always empty

最佳答案

按从左到右的顺序

loadView -> viewDidLoad -> viewWillAppear

loadView 中也没有足够的时间来做这件事,你需要在之前的vc中加载api然后显示需要的 1 ,或者在viewDidLoad里面调用

关于ios - 在 viewDidLoad 之前执行一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59077277/

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