gpt4 book ai didi

ios - Swift 从 URLSession 返回数据

转载 作者:可可西里 更新时间:2023-11-01 03:26:37 26 4
gpt4 key购买 nike

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

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 语句。在这一点上我毫 headless 绪...

最佳答案

您可以使用此完成 block 方法发送最终响应:

例如:我在完成 block 中返回了字符串,成功响应后没有错误,只需将结果传递到 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()
}

您可以使用下面的代码来执行上面的完成 block 功能:

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

}

这将解决您的以下需求。

关于ios - Swift 从 URLSession 返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43048120/

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