gpt4 book ai didi

json - 除非主函数快速完成,否则从函数调用函数不会返回值

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

伙计们,我需要有关 swift 4.0 的帮助

我有一个简单的函数,它调用 json 并用值填充这些变量。

self.getDataFromServer()

在“self.getDataFromServer()”之后,这将使用检索到的数据填充数组。这在 swift 的早期版本(swift 3)上运行得很好。

这是 self.getDataFromServer() 之后的代码,索引超出范围,因为数据未填充(PS:这在 swift 3.0 上工作)

var totalAmount = [String]()
var remainingAmount = [String]()

self.getDataFromServer()

let newTotal = Int(totalAmount[0])! + Int(remainingAmount[0])!
let newRemaining = String(newTotal)


updateDailyData(newRemainingAmount: newRemaining, id: userID[0])

我收到“newTotal”错误,提示索引超出范围。请帮忙。

我注意到在 swift 4 上,每当我调用 JSON 时都会遇到这个问题。JSON函数如下:

func getDataFromServer() {
let dateOfToday = Date()
let strDateOfToday = convertToString(myDate: dateOfToday)
let postString = "ANYTHING HERE";
let myUrl = URL(string: "ANYTHING HERE")
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
request.httpBody = postString.data(using: String.Encoding.utf8);
//Start the task
let task = URLSession.shared.dataTask(with: request) {
(data: Data?, response: URLResponse?, error: Error?) in

if error != nil
{
print("error=\(String(describing: error))")
return
}
let values = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSArray

let success = ((values.value(forKey: "success") as? [String])! as NSArray) as! [String]

if (success[0] == "1")
{
self.totalAmount = ((values.value(forKey: "totalAmount") as? [String])! as NSArray) as! [String]
self.remainingAmount = ((values.value(forKey: "remainingAmount") as? [String])! as NSArray) as! [String]

}
}
//Let's convert response sent from a server side script to a NSDictionary object:
task.resume()
}

最佳答案

这是使用Closure的完美工作解决方案

swift 4

        self.getDataFromServer { (arrTotalAmount, arrRemainingAmount) in
if arrTotalAmount.count > 0, arrRemainingAmount.count > 0 {
// Your code here
let newTotal = Int(totalAmount[0])! + Int(remainingAmount[0])!
let newRemaining = String(newTotal)
updateDailyData(newRemainingAmount: newRemaining, id: userID[0])
}
}

func getDataFromServer(completion: @escaping (_ arrTotalAmount: [String], _ arrRemainingAmount: [String]) -> Void) {
let dateOfToday = Date()
let strDateOfToday = convertToString(myDate: dateOfToday)
let postString = "ANYTHING HERE";
let myUrl = URL(string: "ANYTHING HERE")
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
request.httpBody = postString.data(using: String.Encoding.utf8);
//Start the task
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

if error != nil
{
print("error=\(String(describing: error))")
return
}
let values = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSArray

let success = ((values.value(forKey: "success") as? [String])! as NSArray) as! [String]

if (success[0] == "1")
{
let totalAmount = ((values.value(forKey: "totalAmount") as? [String])! as NSArray) as! [String]
let remaininAmount = ((values.value(forKey: "remainingAmount") as? [String])! as NSArray) as! [String]

completion(totalAmount, remaininAmount)
}
}
//Let's convert response sent from a server side script to a NSDictionary object:
task.resume()
}

关于json - 除非主函数快速完成,否则从函数调用函数不会返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48577747/

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