###やりたいこと
sort関数で投稿した画像を降順に並べ替えたい。
###現在の状況
firebase上に投稿が2つあり、timeIntervalSince1970プロパティなどを使い昇順で表示することはできた。
降順に並べる為に以下のコードを追加した
self.posts.sort(by: { (post1, post2) -> Bool in return post1.creationDate > post2.creationDate }) self.collectionView.reloadData() })
以下がエラーコード
Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
Outlet接続問題ではありません。Storyboardを使わず、コードで書いているからです。
こちらの記事だと
unexpectedly found nil while unwrapping an Optional value
は予期していないnilを発見した時に起きるエラーで、!で宣言した変数はnilが代入されない事を保証するという事らしいのですが、どれを!から?に変えるのかわからないです。
投稿画像を表示するswiftファイル
override func viewDidLoad() { super.viewDidLoad() // Register cell classes ユーザーページに投稿画像を表示させる self.collectionView!.register(UserPostCell.self, forCellWithReuseIdentifier: reuseIdentifier) }
// cell に情報を入れる関数 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // Identifierが"reuseIdentifier(Cell)"でUserPostCellというクラスのcellを取得 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! UserPostCell cell.post = posts[indexPath.item] return cell }
投稿画像のcell
import UIKit class UserPostCell: UICollectionViewCell { // fire var post: Post? { didSet { guard let imageUrl = post?.imageUrl else { return } // 画像のキャッシュを読み込む 画面をロードする度にAPI(database)から読み込まないようにローカルで投稿データの保存する postImageView.loadImage(with: imageUrl) } } let postImageView: UIImageView = { let iv = UIImageView() iv.contentMode = .scaleAspectFill iv.clipsToBounds = true iv.backgroundColor = .lightGray return iv }() // viewDidLoad()的なところ override init(frame: CGRect) { super.init(frame: frame) addSubview(postImageView) postImageView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
投稿データ用のswiftファイル
import Foundation class Post { // 空の変数宣言 // database内のposts項目に合わせる var caption: String! var likes: Int! var imageUrl: String! var ownerUid: String! // 日付 var creationDate: Date! var postId: String! // プロパティの初期化 // Dictionary keyとvalueを持った、関連付けられた配列 AnyObject Int型でもString型でも保管してくれる init(postId: String!, dictionary: Dictionary<String, AnyObject>) { self.postId = postId // Databaseのpostsの中に入りcaptiontというkeyを持ったvalue valueかどうかわかんない if let caption = dictionary["caption"] as? String { self.caption = caption } if let likes = dictionary["likes"] as? Int { self.likes = likes } if let imageUrl = dictionary["imageUrl"] as? String { self.imageUrl = imageUrl } if let ownerUid = dictionary["ownerUid"] as? String { self.ownerUid = ownerUid } if let creationDate = dictionary["creationDate"] as? Double { self.creationDate = Date(timeIntervalSince1970: creationDate) } } }
正直何が原因でエラー表示が出るのかさっぱりわからないです。ヒントでもくださると嬉しいです。よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/04/18 04:18