【问题标题】:Writing CLGeocoder result to Firestore将 CLGeocoder 结果写入 Firestore
【发布时间】:2021-10-07 20:43:15
【问题描述】:

在 Swift 和 Firebase 方面需要一些帮助。

这段代码,在 getFriendlyLocation.swift ...

import UIKit
import CoreLocation
import Firebase
import FirebaseFirestore


class getfriendlyLocation: NSObject {

    let geocoder = CLGeocoder()
    var placemark: CLPlacemark!
    var countryCode: String!
    
    var db: Firestore!

    func initfriendlyLocation(lat:Double, lng:Double) {
        
        let location = CLLocation(latitude: lat, longitude: lng)
        
        geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
            self.processResponse(withPlacemarks: placemarks, error: error)
            
            self.db.collection("main").addDocument(data: ["Country":"US"]) { err in
                if let err = err {
                    print("Error adding document: \(err)")
                } else {
                    print("OK")
                }
            }
        }
    }
}

...在 addDocument() 行产生错误“致命错误:在隐式展开可选值时意外发现 nil”。

完全相同的代码块在闭包之外也能正常工作。

processResponse 块现在不做任何事情,只是检查它是否返回值,它会做。

我从 ViewController.swift 调用 getfriendlyLocation

var friendlyLoc = getfriendlyLocation()
friendlyLoc.initfriendlyLocation(lat: lat, lng: lng)

此代码块在闭包内与在闭包外有什么不同?

谢谢!

正在添加...

func processResponse(withPlacemarks placemarks: [CLPlacemark]?, error: Error?) {
        if let error = error {
            print("ERROR")

        } else {           
            print("OK")
        }
    }
}

【问题讨论】:

  • 你可能需要显示processResponse

标签: swift firebase google-cloud-firestore


【解决方案1】:

问题是您的db 变量为零。你必须在使用它之前做self.db = Firestore.firestore()。您可以将它放在 addDocument 调用之前的任何位置。

【讨论】:

    猜你喜欢
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 2013-04-09
    • 2021-01-19
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多