Swift从URLSession返回数据 [英] Swift return data from 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返回语句。此时我很无能......
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:
对于实例:
我在完成块中返回了String,成功响应后没有错误只是在块中传递结果。
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返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!