ユーザーの緯度経度をRealtimeDatabaseに保存したいです
しかし以下のエラーが出て困っています。解決方法を教えて下さい。
swift
1import UIKit 2import MapKit 3import CoreLocation 4import Firebase 5 6class ViewController: UIViewController { 7 8 @IBOutlet weak var mapView: MKMapView! 9 let locationManager = CLLocationManager() 10 var ref: DatabaseReference! 11 @IBOutlet weak var longitude: UILabel! 12 @IBOutlet weak var latitude: UILabel! 13 let user = Auth.auth().currentUser 14 15 override func viewDidLoad() { 16 super.viewDidLoad() 17 18 locationManager.delegate = self 19 20 ref = Database.database().reference() 21 22 } 23 @IBAction func userLocation(_ sender: Any) 24 { 25 self.ref.child("Test").child(user?.uid).setValue(["latitude": latitude.text]) 26 //Value of optional type 'String?' must be unwrapped to a value of type 'String'と表示されます。これに困っています。 27 } 28 29} 30//以下よりユーザー(自分の現在地取得です) 31extension ViewController: CLLocationManagerDelegate { 32func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { 33 switch status { 34 case .notDetermined: 35 locationManager.requestWhenInUseAuthorization() 36 case .authorizedWhenInUse: 37 locationManager.startUpdatingLocation() 38 default: 39 break 40 } 41 } 42 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 43 if let coordinate = locations.last?.coordinate { 44 // 現在地を拡大して表示する 45 let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01) 46 let region = MKCoordinateRegion(center: coordinate, span: span) 47 mapView.region = region 48 49 } 50 guard let newLocation = locations.last else { 51 return 52 } 53 self.latitude.text = "".appendingFormat("%.4f", newLocation.coordinate.latitude) 54 self.longitude.text = "".appendingFormat("%.4f", newLocation.coordinate.longitude) 55 } 56}
エラーが出る行の前に print(user, user?.uid, latitude, latitude.text) を追加して出力を教えて下さい。
出力とはビルドした後にxcodeに出る下の四角のところですよね?
そもそもBuild Failedで出せないのですがどうしたら良いですか?
どのようにコードを書きましたか?
全部書いてから、初めて実行したのですか?
途中までで実行しながらだったら、
どの段階まで動いてたのか書いてあると
エラー箇所が推測しやすいです。
structの件でご回答頂いた者です。こちらの質問でも同じようにマップにユーザーを表示させたいのが目的です。どのように書いたかに致しましては全て書いてから実行しました。
書いた順番はマップ、現在地の実装→UILabelを置いて自分の緯度経度を表示→firebase関連をpodにインストール→realtime databaseと連結→databaseに保存できないの順です。
まず、UILabelに自分の緯度軽度を表示できるのでしょうか?
実現したいことを考えると、大まかに機能は大きく二つと捉える必要があります。
①自分の位置情報を取得、ネット上に保存
②ネット上からデータをDL、(必要ならRealmに保存?)、地図上に表示
なので、直接DLしたものをそのまま変換して表示する場合は
必ずしも、Realmに保存する必要はないことになります。
Realmへの保存のみの答えでよければ、その回答を載せますが、、、
順番としては②からでもできますが、
その場合はダミーデータが必要ですので、
①、②の順に実装するのが楽でしょう。
自分の緯度経度は表示できています。
思いついたのは自分の緯度経度を取得してそれを数値(Double型)としてrealtimedatabaseに保存し、他ユーザーはそれを自動的に取得し、表示するという風に考えていました。
とりあえずはdatabaseに保存までいきたいと考えているのですが、希望はrealmではなくfirebase(realtimedatabase)です。素人なりに調べてみたところ、リアルタイムで取得が出来るという事でしたので、、
この質問の解決としましては、realtimedatabaseに保存まで出来れば満足です。
hamejiさんの回答の中で言うと①で止まっています。
回答2件
あなたの回答
tips
プレビュー