1
我需要這個函數(它從數據庫獲取一些數據)返回一個字符串,但我很難弄清楚如何。我已經發現了一些類似的問題/解決方案,但我仍然在努力實現一個妥善的解決辦法(我很新與SWIFT)從URLSession完成處理函數返回字符串Swift 3
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
}
}
謝謝!
相當接近[此相關的問題的一種重複數據刪除(HTTPS:/ /stackoverflow.com/questions/24647406/how-to-use-completionhandler-closure-with-return-in-swift)。 –