我需要这个函数(从数据库中获取数据)返回一个字符串,但我遇到了困难。我找到了一些类似的问题/解决方案,但我仍然难以实现一个正确的解决方案(我对Swift还比较陌生)。
class Helper{
static func pReq(jsonURL : String, col : String) -> String {
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: jsonURL)!
let request = URLRequest(url: url)
var string = ""
let downloadTask = session.dataTask(with: request, completionHandler: {(data, response, error) in
if(error == nil){
print("data = \(String(describing: data))")
do{
print(jsonURL)
let dataDownloadedAsJson = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:AnyObject]
print("dataDownloadedAsJson = \(dataDownloadedAsJson)")
do{
if(dataDownloadedAsJson[col] as? String != nil){
string = (dataDownloadedAsJson[col] as? String)!
}
}
}
catch{
}
}
else{
print("Error downloading data. Error = \(String(describing: error))")
}
})
downloadTask.resume()
return string
}
}
谢谢!