因此,我的函数(带有信号量)仅在获取数据之后才返回nil([])。我在封闭中更改了semaphore.signal的位置,但是卡住了。我是新手,希望对您有所帮助。还链接了项目的所有详细信息https://github.com/ablmsky/PatentAnalyzer
功能
extension ViewController{
func dataAndResponse(url: URL?) throws -> [CountryObject] {
var object: [CountryObject] = []
guard let urlString = url else { throw NetworkError.url }
let semaphore = DispatchSemaphore(value: 0)
URLSession.shared.dataTask(with: urlString){ (data, response, error) in
DispatchQueue.main.async(execute: {
guard let data = data else { return }
guard error == nil else { return }
do {
let decoder = JSONDecoder()
let array = try JSONSerialization.jsonObject(with: data) as? [Any] ?? []
let rootElement = array[1]
let rootData = try JSONSerialization.data(withJSONObject: rootElement, options: [])
let countryObjects = try decoder.decode([CountryObject].self, from: rootData)
object = countryObjects
print(countryObjects)//only after returning nil, there will be smthng
} catch let error {
print(error)
}
})
semaphore.signal()
}.resume()
_ = semaphore.wait(timeout: .distantFuture)
return object
}
}
在这里打电话
@IBAction func onButtonClick(_ sender: Any) {
var inputCountry: String
let inputYearFrom: Int
let inputYearTill: Int
inputCountry = labelView.text!
inputYearFrom = Int(labelYearFrom.text!)!
inputYearTill = Int(labelYearTill.text!)!
countriesResponedResult.url = APIPatentManager.getURL(country: Country(rawValue: inputCountry)!)
var countryData: [CountryObject] = []// data which i get from response
do{
countryData = try dataAndResponse(url: countriesResponedResult.url)//here is data is empty
} catch let error{
print(error)
}
print(countryData)
print(inputYearFrom)
print(inputYearTill)
}