当前位置: 首页 > 知识库问答 >
问题:

Swift函数在完成处理之前返回值[重复]

应俊爽
2023-03-14

基本上,我有一个将简单数据发布到服务器的代码,如果发布请求成功,我将返回一个布尔值成功,但似乎在处理数据之前就返回了布尔值,我做错了什么吗?

public func postRequest(rawText: String) -> Bool {
    var success = true
    let destUrl = "http://api.getquesto.com:8080/upload/"
    var request = URLRequest(url: URL(string: destUrl)!)
    request.httpMethod = "POST"
    let postString = rawText
    request.setValue("text/plain", forHTTPHeaderField: "Content-Type")
//    request.setValue("compute", forHTTPHeaderField: "Questo-Query")
//    request.setValue("Fuck you", forHTTPHeaderField: "quizTitle")

    request.httpBody = postString.data(using: .utf8)
    print(request.httpBody!)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(error)")
            success = false
            print(success)

            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        let responseString = String(data: data, encoding: .utf8)
        do {
            if let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: UInt(0))) as? [String: Any] {
                print("json \(json)")
            } else {
                print("can not cast data")
                success = false

            }
        } catch let error {
            print("cant parse json \(error)")
            success = false
            print(success)

        }

        print("responseString = \(responseString)")
        let dataString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
        //print(dataString)
        //print("responseString = \(responseString)")
        constantVariables.rawQuestionData = dataString as! String
        let processedResults = dataString?.replacingOccurrences(of: "\\n", with: " ")
        print("processed results = " + (processedResults! as String))
        let newArray = processedResults!.components(separatedBy: ", \"")
        //print(newArray)

        for index in 0...(newArray.count - 1) {
            if index%2 == 0 {
                constantVariables.questions.insert(newArray[index].replacingOccurrences(of: "\"", with: "").replacingOccurrences(of: "]", with: "").replacingOccurrences(of: "[", with: ""), at: index/2)

                //        ConstantsArray.questionArray.append(newArray[index])
                //        print("question array: " + ConstantsArray.answerArray[index/2])
            }else{
                constantVariables.answers.insert(newArray[index].replacingOccurrences(of: "\"", with: "").replacingOccurrences(of: "]", with: "").replacingOccurrences(of: "[", with: ""), at: (index-1)/2)

                //        ConstantsArray.questionArray.append(newArray[index])
                print("answer array: " + constantVariables.answers[(index-1)/2])

            }
        }
    }
    task.resume()
    print(success)
    return success
    }

共有1个答案

祝花蜂
2023-03-14

这是因为函数直接返回成功的值,dataTask异步工作,因此,函数不应该等到dataTask完成解析来编辑成功的值,即:返回成功是在执行dataTask之前编辑成功的值。

我建议让函数处理< code>completion闭包,而不是直接返回< code>Bool。

您的功能应类似于:

public func postRequest(rawText: String, completion: @escaping (_ success: Bool) -> ()) {
    var success = true
    let destUrl = "http://api.getquesto.com:8080/upload/"
    var request = URLRequest(url: URL(string: destUrl)!)
    request.httpMethod = "POST"
    let postString = rawText
    request.setValue("text/plain", forHTTPHeaderField: "Content-Type")
    //    request.setValue("compute", forHTTPHeaderField: "Questo-Query")
    //    request.setValue("Fuck you", forHTTPHeaderField: "quizTitle")

    request.httpBody = postString.data(using: .utf8)
    print(request.httpBody!)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(error)")
            success = false
            print(success)

            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        let responseString = String(data: data, encoding: .utf8)
        do {
            if let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: UInt(0))) as? [String: Any] {
                print("json \(json)")
            } else {
                print("can not cast data")
                success = false

            }
        } catch let error {
            print("cant parse json \(error)")
            success = false
            print(success)

        }

        print("responseString = \(responseString)")
        let dataString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
        //print(dataString)
        //print("responseString = \(responseString)")
        constantVariables.rawQuestionData = dataString as! String
        let processedResults = dataString?.replacingOccurrences(of: "\\n", with: " ")
        print("processed results = " + (processedResults! as String))
        let newArray = processedResults!.components(separatedBy: ", \"")
        //print(newArray)

        for index in 0...(newArray.count - 1) {
            if index%2 == 0 {
                constantVariables.questions.insert(newArray[index].replacingOccurrences(of: "\"", with: "").replacingOccurrences(of: "]", with: "").replacingOccurrences(of: "[", with: ""), at: index/2)

                //        ConstantsArray.questionArray.append(newArray[index])
                //        print("question array: " + ConstantsArray.answerArray[index/2])
            }else{
                constantVariables.answers.insert(newArray[index].replacingOccurrences(of: "\"", with: "").replacingOccurrences(of: "]", with: "").replacingOccurrences(of: "[", with: ""), at: (index-1)/2)

                //        ConstantsArray.questionArray.append(newArray[index])
                print("answer array: " + constantVariables.answers[(index-1)/2])

            }
        }

        completion(success)
    }
    task.resume()
    print(success)
}

在Swift 3中,您应该使用@转义,有关更多信息,您可能需要检查此答案。

呼叫:

postRequest(rawText: "rawText", completion: { success in
    print(success)
})

现在,它应该等到< code>dataTask完成它的解析,然后,将调用< code>completion中的代码。

 类似资料:
  • 问题内容: 我在Utilities类中使用loadImage方法,并且在通过闭包返回图像时遇到了一些麻烦。基本上因为我的代码可能返回图像或错误,所以在调用该方法时将其分配给image属性是行不通的。 我在类的方法声明中使用的方法是否错误,还是应该以不同的方式调用该方法以预期潜在的不同结果?谢谢 问题答案: 将处理程序添加到您的 loadImage 函数中: 迅捷3 像这样调用func: 斯威夫特2

  • 我对这段代码有一个问题,其中语句是在函数之前触发的,它返回0而不是正确的值。有没有办法在返回之前强制完成?我知道这是一个逻辑问题,因为如果我删除处的注释,它就可以正常工作。 如何在不使用或应用程序中的任何其他类型的超时?原始代码: 编辑代码: 这是StorageInformation类 从接口调用StorageInformation 我还尝试了r2rek的解决方案,得到了相同的结果 欢迎提出任何问

  • 我在ViewDidLoad函数中有一些代码,它将在调用堆栈的末尾设置一个类变量。我试图重构代码,使其成为一个单独的函数,它将返回值,而不是设置类变量。 由于我缺乏swift知识,我不确定哪里出了问题,我的函数似乎返回得太厄尔了,因为我可以在调试器中告诉我,它在被设置为之前跳转到return。 我还可以在调试器中看到,内部函数在返回主函数后调用。 如何等待内部调用完成后再返回?或者什么是正确的快速方

  • 问题内容: 我正在创建一个返回Dictionary的,但是当我在另一个类中调用此方法时,其值为nil。 然后,我尝试在另一个类中调用它,以便可以查看Dictionary 的值并基于该值显示数据。例如, 这里的问题是,当我调用函数时,我在尝试调用字典时收到一个值。 简而言之,我的问题是如何为完成处理程序分配值并在Xcode项目中的其他位置调用它? 问题答案: 您的问题很乱。您的示例代码无效,并且没有

  • 我正在做一个项目,我们正在使用Spring Boot、Spring Batch和Camel。 关于如何在JobExecution数据可用时立即返回它,有什么想法吗?

  • 我仍在为承诺而挣扎,但多亏了这里的社区,我取得了一些进步。 我有一个简单的JS函数,它查询解析数据库。它应该返回结果数组,但显然由于查询的异步性质(因此有承诺),函数在结果之前返回,给我留下一个未定义的数组。 我需要做什么才能让这个函数等待承诺的结果呢? 这是我的代码: