尝试使用以下方法
continuation
如示例代码所示。
struct GetPrice {
static func getThePrice(book: String) async -> Double? {
//..
return await withCheckedContinuation { continuation in
AF.request(url, method: .post, parameters: body, encoding: URLEncoding.default, headers: headers)
.responseData { response in
var statusCode = response.response?.statusCode
//print("response.result ", response.result)
switch response.result {
case .success:
let data = response.data
let s = String(data: data!, encoding: .utf8)
let xml = XMLHash.parse(String(s!))
iListPrice = xml["xxx"].element!.text
theNetPrice = Double(iListPrice)
print(theNetPrice) // this shows correct value
continuation.resume(returning: theNetPrice)
case .failure(let error):
statusCode = error._code
print("status code is: \(String(describing: statusCode))")
print(error)
continuation.resume(returning: theNetPrice)
}
}
}
}
}
用它来做类似的事情
Task {
let price = await GetPrice.getThePrice(book: "MyBook")
if let price = price {
print("The price is: \(price)")
}
}
或者,您可以尝试使用完成处理程序,例如
static func getThePrice(book: String, completion: @escaping (Double?) -> Void) {
//..
AF.request(url, method: .post, parameters: body, encoding: URLEncoding.default, headers: headers)
.responseData { response in
var statusCode = response.response?.statusCode
//print("response.result ", response.result)
switch response.result {
case .success:
let data = response.data
let s = String(data: data!, encoding: .utf8)
let xml = XMLHash.parse(String(s!))
iListPrice = xml["xxx"].element!.text
theNetPrice = Double(iListPrice)
print(theNetPrice) // this shows correct value
completion(theNetPrice)
case .failure(let error):
statusCode = error._code
print("status code is: \(String(describing: statusCode))")
print(error)
completion(theNetPrice)
}
}
}
这样使用它:
GetPrice.getThePrice(book: "MyBook") { price in
if let price = price {
print("The price is: \(price)")
}
}