Hi i am getting following errors while iterating over a custom object with for try await:-
- For-in loop requires '[Photo]' to conform to 'AsyncSequence'
- Type of expression is ambiguous without more context
Custom object:-
enum FetchError: Error { case badImage case badRequest case invalidImageURL case noURL case failedToFetchImage } struct Photo: Codable { let albumId: Int let id: Int let title: String let urlPath: String let thumbnailUrl: String } Working code for fetching 1st image:-
Class ViewController: UIViewController { func fetchAsyncImage(request:URLRequest) async throws -> UIImage { let (data, response) = try await URLSession.shared.data(for: request) guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw FetchError.badRequest } let photos = try JSONDecoder().decode([Photo].self, from: data) guard let imagePath = photos.first?.urlPath, let imageURL = URL.init(string: imagePath) else { throw FetchError.noURL } let (imageData, imageResponse) = try await URLSession.shared.data(from: imageURL) guard (imageResponse as? HTTPURLResponse)?.statusCode == 200 else { throw FetchError.invalidImageURL } guard let firstImage = UIImage(data: imageData) else { throw FetchError.badImage } return firstImage } Issue while performing async sequence on Photo object
func fetchAsyncImage(request:URLRequest) async throws -> [UIImage] { let (data, response) = try await URLSession.shared.data(for: request) guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw FetchError.badRequest } let photos = try JSONDecoder().decode([Photo].self, from: data) guard let imagePath = photos.first?.urlPath, let imageURL = URL.init(string: imagePath) else { throw FetchError.noURL } var imageArr:[UIImage] = [] for await photo in photos { guard let imagePath = photo.urlPath, let imageURL = URL.init(string: imagePath) else { throw FetchError.noURL } do { let (imageData, imageResponse) = try await URLSession.shared.data(from: imageURL) guard (imageResponse as? HTTPURLResponse)?.statusCode == 200 else { throw FetchError.invalidImageURL } guard let image = UIImage(data: imageData) else { throw FetchError.badImage } imageArr.append(image) } catch { throw FetchError.failedToFetchImage } } return imageArr } What i tried for implementing async sequence:-
struct Photo: Codable, AsyncSequence { typealias Element = URL let albumId: Int let id: Int let title: String let urlPath: String let thumbnailUrl: String struct AsyncIterator: AsyncIteratorProtocol { let urlPath: String mutating func next() async throws -> URL? { do { guard let imageURL = URL.init(string: urlPath) else { throw FetchError.noURL } return imageURL } catch { throw FetchError.invalidImageURL } } } func makeAsyncIterator() -> AsyncIterator { AsyncIterator(urlPath: urlPath) } } i am not sure how to iterate over photo objects with "for try await"
![For-in loop requires '[Photo]' to conform to 'AsyncSequence'](https://i.sstatic.net/c4a9M.png)