难以添加priceLevel与google places api

时间:2018-01-10 19:01:54

标签: ios swift uitableview google-places-api swift4

使用Google Places API我添加了该地点的网站和priceLevel。我创建了这个函数:

func didClickWebsite(place: EClass) {
   Zone.PlaceDetails(place: place) { (place) in
        if let website = place.details?["website"] as? String, let url = URL(string: website) {
           let svc = SFSafariViewController.init(url: url)
           self.navigationController?.pushViewController(svc, animated: true)
        }
    }
}

@IBAction func goToWebSite(_ sender: Any) {
    if let place = place, let delegate = delegate {
       delegate.didClickWebsite(place: place)
    }
}

当我按下按钮时,它会发送到我所在的地方。对于priceLevel,我试图模仿相同的概念。我在自定义tableViewCell类中创建了它:

func update(place:EClass) {
    self.place = place
    myLabel.text = place.name
    myImage.image = nil
    myLabel2.text = place.getDescription()
    if let url = place.photos?.first?.getPhotoURL(maxWidth: maxWidht) {
        myImage.af_setImage(withURL: url)
    }

    Zone.PlaceDetails(place: place) { (place) in
        if let price = place.details?["price_level"] as? Int, let PriceLevel: Int = Int(price) {
            let o = Int(PriceLevel)
            self.myPriceLabel.text = "\(o)"          
        }
    }
}

我希望priceLevel通过标签显示在tableview中,但它不起作用。当我在我的tableView中运行应用程序时myPriceLabel保持不变"标签"。我该如何解决这个问题?

更新

static func PlaceDetails(place:EClass, completion: @escaping (EClass) -> Void) {

    guard place.details == nil else {
        completion(place)
        return
    }

    var params : [String : Any]
    params = [
        "key" : AppDelegate.googlePlacesAPIKey,
        "placeid" : place.placeId,
    ]

    Alamofire.request(googlePlaceDetailsHost, parameters: params, encoding: URLEncoding(destination: .queryString)).responseJSON { response in
        let value = response.result.value as? [String : Any]
        place.details = (value)?["result"] as? [String : Any]
        completion(place)
    }
}

1 个答案:

答案 0 :(得分:0)

首先,这条线是不必要的:let PriceLevel: Int = Int(price)。您的编译器可能会向您发出警告,告诉您不能对非可选值使用可选绑定。由于您已经将price作为Int解包,因此无需将其传递到另一个Int init。并且肯定不需要将其传递到第Int个初始化行let o = Int(PriceLevel)

接下来的事情是,由于我假设Zone.PlaceDetails是一个网络呼叫,您需要确保在主队列上更新myPriceLabel文本。也许PlaceDetails已经在主队列上执行完成处理程序,在这种情况下,您可以忽略此注释。

最后,如果您的通话中未收到details个对象,或details没有该键的值,则您不会提供后备选项price_level“,或者值不是Int。你可以添加一个else来处理它:

Zone.PlaceDetails(place: place) { (place) in
    //Make sure your labels are being set on the main queue
    DispatchQueue.main.async {
        if let price = place.details?["price_level"] as? Int {
            self.myPriceLabel.text = "\(price)"          
        } else {
            self.myPriceLabel.text = "UNKNOWN" //Or whatever you want it to say
        }
    }
}

如果您每次我建议查看API文档以获得price_level值实际提供的值时,您将获得“未知”。也许它实际上是FloatString或其他。