我是Swift的新手,正在尝试向本地主机发出http请求。像异步,关闭之类的快速处理httprequest的内容太多了,这使我感到困惑。我已经实现了urlSession,并且可以在takeRequest中打印从completionhandler接收到的数据。我正在尝试从takeRequest函数返回值并将其传递给PopUpTextView。我该怎么办?
PareseRequest.swift
func StartRequest(urlRequest: URLRequest,
completionHandler:@escaping ([[String:Any]], Error?) -> Void){
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
// Check if Error took place
if let error = error {
print("Error took place \(error)")
return
}
// Read HTTP Response Status code
if let response = response as? HTTPURLResponse {
print("Response HTTP Status code: \(response.statusCode)")
}
// Convert HTTP Response Data to a simple String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
//completionHandler(dataString, nil)
//print("Response data string:\n \(dataString)")
do{
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]{
print("imhere")
if let names = json["list"] as? [[String:Any]] {
// print("json names")
// print(names)
completionHandler(names, nil)
}
else{
print("json did not load")
}
}
}catch let error as NSError{
print("Failed to load: \(error.localizedDescription)")
}
}
}
task.resume()
}
func takeReqeust(completionHandler:@escaping ([[String:Any]], Error?) -> Void) -> Void{
let url = URL(string: "http://localhost:3000")
var request = URLRequest(url: url!)
request.httpMethod = "GET"
var new_data: String = ("")
StartRequest(urlRequest: request) { (data, error) in
print("I'm here")
completionHandler(data,nil)
new_data = data[0].description
print(new_data)
}
}
PopUpTextView.Swift
struct PopUpTextView: View {
var body: some View {
Text()
}
这是您的代码快照的最简单的演示解决方案
struct PopUpTextView: View {
@State private var data = "Loading..."
var body: some View {
Text(data)
.onAppear {
takeReqeust { (data, error) in // original typo? - takeRequest?
if let first = data.first {
self.data = first
} else {
self.data = "No data"
}
}
}
}
}