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

标签 json swift xcode function

伙计们,我需要有关 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/

相关文章:

objective-c - 隐藏状态栏会留下空白

ios - 向 SwiftUI TextField 添加不可编辑的后缀

ios - 为参数 "invalid value"提供了一个 'appIdName'?

json - 无法加载 JSON 数据以在 ListView 中显示

json - Grunt 不会从 grunt-json-server 运行 json_server 任务

java - 验证 Jackson 中的嵌套对象

swift - 我想在 Firebase 中向子节点添加一个节点,但是当我添加值时,它会删除之前发送到数据库的所有其他数据 - Swift

python - django rest framework,order_by 来自 serializers.py 文件的 JSON

ios - 无法在 Collection View 中显示存储在 App Delegate 中的数组数据

ios - 使用闭包作为函数参数时,Swift 不带逗号的单独参数