質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Firebase

Firebaseは、Googleが提供するBasSサービスの一つ。リアルタイム通知可能、並びにアクセス制御ができるオブジェクトデータベース機能を備えます。さらに認証機能、アプリケーションのログ解析機能などの利用も可能です。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

944閲覧

swift RealtimeDatabase ユーザ情報を取得できない(保存はできてます)

globalplus

総合スコア119

Firebase

Firebaseは、Googleが提供するBasSサービスの一つ。リアルタイム通知可能、並びにアクセス制御ができるオブジェクトデータベース機能を備えます。さらに認証機能、アプリケーションのログ解析機能などの利用も可能です。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2019/11/28 20:31

編集2019/11/28 20:32

UIButtonを押してrealtimedatabaseからlatitude.textを取得したいのですが不明なnilが返ってきてエラーになります(Unexpectedly found nil while unwrapping an Optional value)
このページを参考にしながらやったのですが、解決方法がわかりません。アドバイスお願いします。

viewcontroller

1import UIKit 2import MapKit 3import CoreLocation 4import Firebase 5 6class FirstViewController: UIViewController, CLLocationManagerDelegate { 7 8 @IBOutlet weak var mapView: MKMapView! 9 @IBOutlet weak var latitude: UILabel! 10 @IBOutlet weak var longitude: UILabel! 11 let user = Auth.auth().currentUser?.uid 12 let locationManager = CLLocationManager() 13 var ref: DatabaseReference! 14 var otherUserLatitude: String? = nil 15 var otherUserLongitude: String? = nil 16 17 override func viewDidLoad() { 18 super.viewDidLoad() 19 ref = Database.database().reference() 20 locationManager.delegate = self as! CLLocationManagerDelegate 21 22 } 23 //保存できてます 24 @IBAction func userLocation(_ sender: Any) 25 { 26 let userCoordinate = ["userLatitude": latitude.text] 27 ref.child("users").setValue(["userCoordinate": userCoordinate]) 28 print("位置情報を保存しました") 29 } 30 @IBAction func othersLocation(_ sender: Any) 31 { 32 //Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional valueのエラー 33 ref.child("userLatitude").child(user!).observeSingleEvent(of: .value, with: { (snapshot) in 34 let value = snapshot.value as? NSDictionary 35 let otherUserLatitude = value?["userLatitude"] as? String 36 print("ユーザー緯度:", otherUserLatitude) 37 }) 38 } 39 40 func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { 41 switch status { 42 case .notDetermined: 43 locationManager.requestWhenInUseAuthorization() 44 case .authorizedWhenInUse: 45 locationManager.startUpdatingLocation() 46 default: 47 break 48 } 49 } 50 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 51 if let coordinate = locations.last?.coordinate { 52 // 現在地を拡大して表示する 53 let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01) 54 let region = MKCoordinateRegion(center: coordinate, span: span) 55 mapView.region = region 56 } 57 guard let newLocation = locations.last else { 58 return 59 } 60 self.latitude.text = "".appendingFormat("%.4f", newLocation.coordinate.latitude) 61 self.longitude.text = "".appendingFormat("%.4f", newLocation.coordinate.longitude) 62 let location = locations.first 63 let latitude = location?.coordinate.latitude 64 let longitude = location?.coordinate.longitude 65 66 print("緯度: (latitude!)\n経度: (longitude!)") 67 } 68 69 70}

realtimedatabase内の情報
イメージ説明

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

hayabusabusash

2019/11/29 02:14

変数userがもしかしたらnilになっているとかはありませんか? printとかで値を表示したらちゃんと表示されるか確認してみてもらえませんか?
globalplus

2019/11/29 05:52

ref.child("userLatitude").child(user!).observeSingleEvent(of: .value, with: { (snapshot) in を ref.child("userLatitude").observeSingleEvent(of: .value, with: { (snapshot) in にして実行してみると print("ユーザー緯度:", otherUserLatitude) で ユーザー緯度: nil が出力されます。
hayabusabusash

2019/11/29 05:56

ref.child("userLatitude").child(user!).observeSingleEvent(of: .value, with: { (snapshot) in の一つ上の行に print(user) を追加して結果を確認していただけませんか?
hayabusabusash

2019/11/29 06:03

ありがとうございます!それが原因っぽいですね。 ということはAuthにサインインしていないもしくは失敗している可能性があります。 確認ですが、Authにサインインする処理は実装されていますか?
globalplus

2019/11/29 06:05

Authにサインインすると言うのを具体的に教えていただけませんか? Bundle Identifierを使ってfirebaseとの接続は出来てます。
popai306

2019/11/29 06:07

横からすみません。 そもそもsetValue時にuserId使ってないので ``` @IBAction func userLocation(_ sender: Any) { let userCoordinate = ["userLatitude": latitude.text] ref.child("users").setValue(["userCoordinate": userCoordinate]) print("位置情報を保存しました") } ``` これで取れませんかね? ``` @IBAction func othersLocation(_ sender: Any) { //Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional valueのエラー ref.child("users").child("userCoordinate").observeSingleEvent(of: .value, with: { (snapshot) in let value = snapshot.value as? NSDictionary let otherUserLatitude = value?["userLatitude"] as? String print("ユーザー緯度:", otherUserLatitude) }) } ```
globalplus

2019/11/29 06:13

出力、ユーザー緯度: Optional("35.5636") で取れました! ほんとに困ってたので助かりました!ありがとうございます! ただprint(user)がnilなのは気になるところですが、、 ベストアンサーをさせて頂きたいので回答を編集して頂けると助かります。
globalplus

2019/11/29 06:22

hayabusabusashもありがとうございました!Authについて調べてみます!
guest

回答1

0

ベストアンサー

これで取れませんかね?

@IBAction func othersLocation(_ sender: Any) { //Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional valueのエラー ref.child("users").child("userCoordinate").observeSingleEvent(of: .value, with: { (snapshot) in let value = snapshot.value as? NSDictionary let otherUserLatitude = value?["userLatitude"] as? String print("ユーザー緯度:", otherUserLatitude) }) }

あるべきはsetValue時に

let userCoordinate = ["userLatitude": latitude.text] ref.child("users").child(user!).setValue(["userCoordinate": userCoordinate])

取得するときは

ref.child("users").child(user!).child("userCoordinate")...

投稿2019/11/29 03:00

編集2019/11/29 06:21
popai306

総合スコア157

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

globalplus

2019/11/29 05:50

逆にして実行しても同じエラーが出ます。。
popai306

2019/11/29 06:23

上のやり取りで ``` Auth.auth().currentUser?.uid ``` によるuidの取得ができていないようですが、そもそもAuthLoginしてます?
globalplus

2019/11/29 06:27

⚠︎上の自分のコメントは回答編集前のものです。 上記に記載されているコードで保存、取得が上手くいきます。
globalplus

2019/11/29 06:28

ログイン機能は実装してないです。。
popai306

2019/11/29 06:31

あー、それだとuidは取れないですね。。。 Authログイン後にuidが払い出されるので。 hayabusabusashさんが貼ってくれているように、下記URLを参考にしながら作ってみてください! https://firebase.google.com/docs/auth/ios/start?hl=ja
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問