在Swift

时间:2017-01-19 18:14:03

标签: ios swift uicollectionview uicollectionviewcell clgeocoder

在我的代码中,我正在调用Apple地理编码器:

private func callGoogleReverseGeocodingWebservice(location: CLLocationCoordinate2D) {

    let geoCoder = CLGeocoder()
    let location = CLLocation(latitude: location.latitude, longitude: location.longitude)
    self.defaults.synchronize()
    if (!self.alreadyShowedHashtagSuggestionPanel && defaults.object(forKey: "doNotShowHashtags") == nil) {
        self.alreadyShowedHashtagSuggestionPanel = true
    geoCoder.reverseGeocodeLocation(location, completionHandler: { placemarks, error in
        guard let addressDict = placemarks?[0].addressDictionary else {
            return
        }
        self.suggestedHashtags.removeAllObjects()

        if let street = addressDict["Thoroughfare"] as? String {
            self.suggestedHashtags.add(street)
        }
        if let city = addressDict["City"] as? String {
            self.suggestedHashtags.add(city)
        }
        if let country = addressDict["Country"] as? String {
            self.suggestedHashtags.add(country)
        }

        if(self.suggestedHashtags.count > 0) {
            print(self.suggestedHashtags.count)
            print("here")
            DispatchQueue.main.async {
                self.hashtagsCollectionView.reloadData()
            } 
        } else {
            print("there's nothing here")
        }

    })
    }
}

上述方法的每个结果都放在一个数组中,该数组用于方法:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    print("cellForRow")
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "hashtagCell", for: indexPath) as! HashtagCollectionViewCell

    let hashtagName:String =  self.suggestedHashtags[(indexPath as NSIndexPath).item] as! String
    cell.hashtagName.textColor = UIColor.lightGray
    cell.hashtagName.font = font
    cell.hashtagName.text = hashtagName
    print("this is \(hashtagName)")
    return cell 
}

不幸的是,有时这一行:

let hashtagName:String =  self.suggestedHashtags[(indexPath as NSIndexPath).item] as! String

抛出错误,说:

libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

我不确定是什么原因造成了这个问题,从我看过的内容看来,地理编码器似乎避免了太多的请求,所以我认为在查询太多之后 - 它会返回空数据,因此{{ 1}}抛出错误 - 但这只是我随意的想法,也许还有其他我可能会遗漏的东西?

1 个答案:

答案 0 :(得分:0)

您不应将IndexPath强制转换为NSIndexPath,否则可能会导致此类问题。 所以请尝试更改此行

let hashtagName:String = self.suggestedHashtags[(indexPath as NSIndexPath).item] as! String

let hashtagName = (self.suggestedHashtags[indexPath.item] as? String) ?? ""

希望这会对你有所帮助