gpt4 book ai didi

ios - URLSessionDataTask没有成员“映射” Swift 5

转载 作者:行者123 更新时间:2023-12-01 22:00:13 24 4
gpt4 key购买 nike

您好,这是一个错误,我不知道如何解决。从本教程中:

Reusable Image Cache in Swift

5
码:

final class ImageLoader {

private let cache = ImageCache()

func loadImage(from url: URL) -> AnyPublisher<UIImage?, Never> {
if let image = cache[url] {
return Just(image).eraseToAnyPublisher()
}
return URLSession.shared.dataTask(with: url)
.map { (data, response) -> UIImage? in return UIImage(data: data) }
.catch { error in return Just(nil) }
.handleEvents(receiveOutput: {[unowned self] image in
guard let image = image else { return }
self.cache[url] = image
})
.subscribe(on: .background)
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
}

更新:

如果您使用dataTaskPublisher:
enter image description here

最佳答案

为此,您必须使用dataTaskPublisher而不是dataTask本身

final class ImageLoader {

private let cache = ImageCache()

func loadImage(from url: URL) -> AnyPublisher<UIImage?, Never> {
if let image = cache[url] {
return Just(image).eraseToAnyPublisher()
}
return URLSession.shared.dataTaskPublisher(for: url)
.map { UIImage(data: $0.data) }
.catch { error in return Just(nil) }
.handleEvents(receiveOutput: {[unowned self] image in
guard let image = image else { return }
self.cache[url] = image
})
.subscribe(on: DispatchQueue.global(qos: .background))
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
}

关于ios - URLSessionDataTask没有成员“映射” Swift 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60236376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com