本文介绍了Swift 从 URLSession 返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从我的 HTTPrequest 返回数据,我也无法让完成处理程序工作.所以请帮助我解决这个问题:

I cannot return data from my HTTPrequest and I can't get completion handlers to work either. So please assist me in my quest to solve this issue:

public static func createRequest(qMes: message, location: String, method: String) -> String{
    let requestURL = URL(string: location)
    var request = URLRequest(url: requestURL!)

    request.httpMethod = method
    request.httpBody = qMes.toString().data(using: .utf8)

    let requestTask = URLSession.shared.dataTask(with: request) {
        (data: Data?, response: URLResponse?, error: Error?) in

        if(error != nil) {
            print("Error: (error)")
        }

        return String(data: data!, encoding: String.Encoding.utf8) as String!
    }
    requestTask.resume()
}

它在 void 函数中期待非 void return 语句.在这一点上我一无所知...

It is excpecting non-void return statement in void function. At this point I'm clueless...

推荐答案

你可以使用这个完成块方法发送最终响应:

You can use this completion block method to send the final response:

例如:我在完成块中返回了字符串,成功响应后没有错误就将结果传递到块中.

For Instance:I have returned String in completion block, after successful response without error just pass the result in block.

  public func createRequest(qMes: String, location: String, method: String , completionBlock: @escaping (String) -> Void) -> Void
    {

        let requestURL = URL(string: location)
        var request = URLRequest(url: requestURL!)

        request.httpMethod = method
        request.httpBody = qMes.data(using: .utf8)

        let requestTask = URLSession.shared.dataTask(with: request) {
            (data: Data?, response: URLResponse?, error: Error?) in

            if(error != nil) {
                print("Error: (error)")
            }else
            {

                let outputStr  = String(data: data!, encoding: String.Encoding.utf8) as String!
                //send this block to required place
                completionBlock(outputStr!);
            }
        }
        requestTask.resume()
    }

您可以使用以下代码来执行上述完成块功能:

You can use this below code to execute the above completion block function:

 self.createRequest(qMes: "", location: "", method: "") { (output) in

        }

这将解决您的以下需求.

This will solve your following requirement.

这篇关于Swift 从 URLSession 返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 05:44