xcode 如何在DispatchGroup().notify中返回值?

9udxz4iz  于 2023-02-09  发布在  其他
关注(0)|答案(1)|浏览(98)

我需要在DispatchGroup()返回图像。通知这是我的代码:

func getImage() -> UIImage? {
    guard isLoaded else { return nil }
    var image: UIImage?
    let group = DispatchGroup()
    group.enter()
    survice.getWeatherImage(data!.list.first!.weather.first!!.icon) { uiimage in
        image = uiimage
        group.leave()
    }
    group.notify(queue: .main) {
        return image
    }
}

我有一个错误:无法将类型“UIImage?”的值转换为闭包结果类型“Void”
请帮帮我,我试着做每件事,但我不知道

hgc7kmma

hgc7kmma1#

看起来你正在尝试使用DispatchGroup使一个异步函数同步,但这不是API的工作方式。如果你想了解更多关于DispatchGroup的信息,请再问一个问题。现在,让我们来解决你遇到的问题。
你可以用两种不同的方法来解决这个问题。
1.您可以考虑在getImage函数中使用一个完成闭包,以便在图像准备就绪时将图像传递回调用者:

func getImage(completion: @escaping (UIImage?) -> Void) {
    guard isLoaded else {
        completion(nil)
        return
    }

    service.getWeatherImage(data!.list.first!.weather.first!!.icon) { image in
        completion(image)
    }
}

这样称呼它:

getImage { image in
    // Use the `image` here
}

或者,您可以将其编写为async函数(有关更多信息,请参见"Meet async/await in Swift")。

func getImage() async -> UIImage? {
    guard isLoaded else {
        return nil
    }

    let url = data!.list.first!.weather.first!!.icon
    return await withCheckedContinuation { continuation in
        service.getWeatherImage(url) { image in
            continuation.resume(returning: image)
        }
    }
}

这样称呼它:

let image = await getImage()
// use image

如果调用它的函数本身不是异步的,你可能需要在一个任务中调用异步函数:

Task {
    let image = await getImage()
    // use image
}

相关问题