前提
XcodeでFirestoreのデータを取得しようとしています。
ビルドは成功するのですが、シミュレーターで実行するとうまくいきません。
プロジェクトとFirebaseは連携できていることは確認できています。
回答していただけると大変ありがたいです。
よろしくお願いします。
実現したいこと
初期化を成功させ、Firebaseのデータを正確に渡すこと。
発生している問題・エラーメッセージ
LocationsViewModel.swiftの3行目
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
該当のソースコード
LocationsViewModel.swift
1init() { 2 let locations = FirebaseViewModel().stores 3 self.locations = locations 4 self.mapLocation = locations.first! 5 self.updateMapRegion(location: locations.first!) 6 }
FirebaseViewModel.swift
1import SwiftUI 2import FirebaseFirestore 3import MapKit 4 5class FirebaseViewModel: ObservableObject { 6 @Published var stores = [Location]() 7 8 9 func getData() { 10 11 let db = Firestore.firestore() 12 13 db.collection("stores").getDocuments { snapshot, error in 14 if error == nil { 15 // No errors 16 if let snapshot = snapshot { 17 DispatchQueue.main.async { 18 self.stores = snapshot.documents.map { d in 19 return Location(name: d["name"] as? String ?? "", 20 category: d["category"] as? String ?? "", 21 link: d["url"] as? String ?? "", 22 description: d["description"] as? String ?? "", 23 coordinates: d["coordinates"] as! GeoPoint, 24 id: d.documentID) 25 } 26 } 27 } 28 } 29 else { 30 } 31 } 32 33 } 34} 35
Locations.swift
1import Foundation 2import MapKit 3import FirebaseFirestore 4 5struct Location: Identifiable, Equatable { 6 7 var name: String 8 var category: String 9 var link: String 10 var description: String 11 var coordinates: GeoPoint 12 var id: String 13 14 static func == (lhs: Location, rhs: Location) -> Bool { 15 lhs.id == rhs.id 16 } 17 var locationCoordinate: CLLocationCoordinate2D { 18 CLLocationCoordinate2D( 19 latitude: coordinates.latitude, 20 longitude: coordinates.longitude) 21 } 22 23 struct Coordinates: Hashable, Codable { 24 var latitude: Double 25 var longitude: Double 26 } 27 28}
補足情報(FW/ツールのバージョンなど)
macOS バージョン12.4 1.1GHz 4コアIntel Core i5
Xcodeバージョン13.4.1
あなたの回答
tips
プレビュー