【问题标题】:Getting NSException while filling UICollectionView in Swift在 Swift 中填充 UICollectionView 时获取 NSException
【发布时间】:2017-06-04 13:40:50
【问题描述】:

在我的代码中,我调用了 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) 

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

【问题讨论】:

  • 发布完整的异常消息。如果您有异常断点,您可能需要删除/跳过它,以便将完整消息记录在控制台中。

标签: ios swift uicollectionview uicollectionviewcell clgeocoder


【解决方案1】:

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

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

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

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多