SwiftでDogAPIを使った写真表示アプリを作っていますがエラーで詰まっています。

動かせてはいないのですが、
ビルドエラーになっているところをポイントに
書いてみますね。

AlamofireでSwift Concurrencyを使用する場合は次の引用にある通りに記述するみたいですね。
*他にも書き方があるみたいですので、リンク先も見てみると良いかもしれませんね。

Using Alamofire with Swift Concurrency

swift

1let value = try await AF.request(...).serializingDecodable(TestResponse.self).value

Alamofire/Documentation/AdvancedUsage.md at master · Alamofire/Alamofire · GitHub

該当のソースコードを修正すると次のような感じになるかなと思います。

swift

1 let apiUrl = "https://dog.ceo/api/breed/\(selectedBreed)/images/random/10"2 3 // `try!`の部分は例外をどう扱うのか要件に合わせて検討してみてください。4 let photoResponse = try! await AF.request(apiUrl).serializingDecodable(PhotoResponse.self).value 5 6 self.imageURLs = photoResponse.message.compactMap { URL(string: $0) }7 self.dogPhoto.reloadData()8 9 // `try!`の部分は例外をどう扱うのか要件に合わせて検討してみてください。10 try! await loadImages()

追記です。

コメントありがとうございます。

collectionViewに遷移した時に画像が出ないのは別問題かなと思っているので

collectionView(_,cellForItemAt:)メソッドの中でセルの内容を設定する必要があるかなと思います。

loadImages()メソッドでセルの値を設定しているように見えますが、
セルのインスタンスは再利用する仕組みがUIKitにありますので、
(collectionView.dequeueReusableCell(withReuseIdentifier:for:)メソッドがそれですね。)
この仕組みに従うように実装する方が良いかなと思いました。
・・伝わりますかね・・

Discussion
Your implementation of this method is responsible for creating, configuring, and returning the appropriate cell for the given item. You do this by calling the dequeueReusableCell(withReuseIdentifier:for:) method of the collection view and passing the reuse identifier that corresponds to the cell type you want. That method always returns a valid cell object. Upon receiving the cell, you should set any properties that correspond to the data of the corresponding item, perform any additional needed configuration, and return the cell.
このメソッドの実装は、指定されたアイテムに適切なセルを作成、構成、および返す責任を負います。そのためには、コレクション・ビューの dequeueReusableCell(withReuseIdentifier:for:) メソッドを呼び出し、必要なセル・タイプに対応する再利用識別子を渡します。このメソッドは常に有効なセル・オブジェクトを返す。セルを受け取ったら、対応するアイテムのデータに対応するプロパティを設定し、必要な追加設定を行い、セルを返す。

collectionView(_:cellForItemAt:) | Apple Developer Documentation

コメントを投稿

0 コメント