Как получить местоположение с помощью GeoPoint из Cloud Firestore? - PullRequest
0 голосов
/ 10 января 2020

У меня проблемы с попыткой настроить мой код при инициализации местоположения моих магазинов с помощью GeoPoint из Cloud Firestore. я получаю 2 ошибки при попытке настроить инициализатор, чтобы иметь возможность обрабатывать данные, я прокомментировал ошибки, где проблема.

ошибки отображаются в моем private init?(documentID: String, dictionary: [String: Any]) {:

'let' не может отображаться внутри другого шаблона 'var' или 'let' & Ожидаемый шаблон

Инициализатор условного связывания должен иметь необязательный тип, а не 'CLLocationCoordinate2D'

Я пытался изменить свою модель, чтобы иметь более чистый код, чтобы данные обрабатывались лучше и были менее глючными и менее сложными, я просто борюсь с настройкой GeoPoint в этой структуре.

struct Stores {
    var documentID: String
    var name: String
    var category: String
    var price: Int
    var imageURL: URL
    var description: String
    var location: CLLocationCoordinate2D
    var distanceFromUser: Double
    var rating: Int

//    self.distanceFromUser = (CLLocationManager().location?.distance(from: CLLocation(latitude: location.latitude, longitude: location.longitude)))!
//    print("look here!", self.distanceFromUser)
}

extension Stores: DocumentSerializable {

     init(name: String,
          category: String,
          price: Int,
          description: String,
          rating: Int,
          imageURL: URL,
          location: CLLocationCoordinate2D,
          distanceFromUser: Double) {
       let document = Firestore.firestore().products.document()
       self.init(documentID: document.documentID,
                 name: name,
                 category: category,
                 price: price,
                 imageURL: imageURL,
                 description: description,
                 location: location,
                 distanceFromUser: (CLLocationManager().location?.distance(from: CLLocation(latitude: location.latitude, longitude: location.longitude)))!,
                 rating: rating)
     }

     /// Initializes a stores from a documentID and some data, ostensibly from Firestore.
     private init?(documentID: String, dictionary: [String: Any]) {
        guard let name = dictionary["name"] as? String,
           let category =  dictionary["category"] as? String,
           let price =  dictionary["price"] as? Int,
           let rating = dictionary["rating"] as? Int,
           let description =  dictionary["description"] as? String,
           let imageURLString = dictionary["photoURL"] as? String,

           //ERRORS HERE\\
           let geoPoint = dictionary["location"] as? GeoPoint else { return nil}
           let latitude = geoPoint.latitude,
           let longitude = geoPoint.longitude, // errors: 'let' cannot appear nested inside another 'var' or 'let' pattern & Expected pattern

       guard let location =  CLLocationCoordinate2D(latitude: latitude, longitude: longitude) else { return nil }     // error: Initializer for conditional binding must have Optional type, not 'CLLocationCoordinate2D'
           // ERRORS END \

       guard let imageURL =  URL(string: imageURLString) else { return nil }

       self.init(documentID: documentID,
                 name: name,
                 category: category,
                 price: price,
                 imageURL: imageURL,
                 rating: rating,
                 description: description,
                 location: location)
     }

     init?(document: QueryDocumentSnapshot) {
        self.init(documentID: document.documentID, dictionary: document.data())
     }

     init?(document: DocumentSnapshot) {
        guard let data = document.data() else { return nil }
        self.init(documentID: document.documentID, dictionary: data)
     }

     /// The dictionary representation of the restaurant for uploading to Firestore.
     var documentData: [String: Any] {
        return [
         "name": name,
         "category": category,
         "price": price,
         "imageURL": imageURL.absoluteString,
         "description": description
         "rating": rating,
         "location": location
       ]
     }
}

public protocol DocumentSerializable {

    init?(document: QueryDocumentSnapshot)

    init?(document: DocumentSnapshot)

    var documentID: String { get }

    var documentData: [String: Any] { get }

 }

extension Firestore {
  /// Returns a reference to the top-level stores collection.
    var stores: CollectionReference {
        return self.collection("stores")
    }
}

1 Ответ

0 голосов
/ 10 января 2020

Вы просто забыли закончить свое длинное выражение guard знаком else { return nil }. Замените

let geoPoint = dictionary["location"] as? GeoPoint,

на

let geoPoint = dictionary["location"] as? GeoPoint else { return nil }

Затем поместите

let latitude = geoPoint.latitude
let longitude = geoPoint.longitude

ниже, и вам должно быть хорошо go. Последние два назначения не могут потерпеть неудачу, поэтому вы можете поместить их в оператор guard.

...