如何从数据源填充TableView单元格?我目前收到错误

时间:2019-06-26 08:02:33

标签: swift uitableview mapbox

我正在尝试从Mapbox Geocoder返回一个经过地理编码的地标数组到TableView单元,但是我收到一个错误(UITableView中的断言失败并且无法获取一个单元)。我在代理或索引路径上做错了什么吗?我已经看过类似的问题,但无法解决。

我正在使用情节提要;我已经三遍检查了情节提要中的单元格标识符,以确保它与“带有标识符”对齐。

编辑:通过将'cellForRowAt indexPath:NSIndexPath'更改为'cellForRowAt indexPath:IndexPath',我能够消除错误。

现在,当我在SearchBar中输入文本时,它将返回数组,但是即使有数据,单元格也为空。 Empty Cells Picture

import UIKit
import MapboxGeocoder

class LocationSearchTable: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    var placemarkResults: [GeocodedPlacemark] = []

    func forwardGeocoding(addressQuery: String) {

        let geocoder = Geocoder(accessToken: "//OMITTED//")

        let options = ForwardGeocodeOptions(query: addressQuery)

        options.allowedScopes = [.address]
        options.allowedISOCountryCodes = ["US"]
        options.autocompletesQuery = true


        let _ = geocoder.geocode(options)  { (placemarks, attribution, error) in
            guard let placemarks = placemarks, !placemarks.isEmpty else {
                return
            }

            self.placemarkResults = placemarks

        }
        print(placemarkResults)
    }
}

extension LocationSearchTable: UISearchResultsUpdating {
    func updateSearchResults(for searchController: UISearchController) {

        guard let searchBarText = searchController.searchBar.text else { return }

        let _ = forwardGeocoding(addressQuery: searchBarText)

        self.tableView.reloadData()

    }

}

extension LocationSearchTable {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return placemarkResults.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
        let selectedItem = placemarkResults[indexPath.row].place
        cell.textLabel?.text = selectedItem?.name
        cell.detailTextLabel?.text = ""
        return cell
    }
}
2019-06-26 00:45:22.179129-0700 Ride Sharing App[91152:18783310] *** Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKitCore_Sim/UIKit-3698.103.12/UITableView.m:9655
2019-06-26 00:45:22.186549-0700 Ride Sharing App[91152:18783310] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView (<UITableView: 0x7f8fb398e200; frame = (0 0; 414 896); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x6000018395c0>; layer = <CALayer: 0x60000161fca0>; contentOffset: {0, -144}; contentSize: {414, 44}; adjustedContentInset: {144, 0, 34, 0}>) failed to obtain a cell from its dataSource (<Ride_Sharing_App.LocationSearchTable: 0x7f8fb2d69660>)'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010e2196fb __exceptionPreprocess + 331
    1   libobjc.A.dylib                     0x000000010b3b7ac5 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010e219482 +[NSException raise:format:arguments:] + 98
    3   Foundation                          0x000000010ae05927 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 194
    4   UIKitCore                           0x0000000115f0799f -[UITableView _configureCellForDisplay:forIndexPath:] + 433
    5   UIKitCore                           0x0000000115f1a6bf -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 911
    6   UIKitCore                           0x0000000115f1ab65 -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 73
    7   UIKitCore                           0x0000000115ee2d20 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2870
    8   UIKitCore                           0x0000000115f02e37 -[UITableView layoutSubviews] + 165
    9   UIKitCore                           0x00000001161af9c1 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1417
    10  QuartzCore                          0x000000010ec85eae -[CALayer layoutSublayers] + 173
    11  QuartzCore                          0x000000010ec8ab88 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 396
    12  QuartzCore                          0x000000010ec96ee4 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 72
    13  QuartzCore                          0x000000010ec063aa _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 328
    14  QuartzCore                          0x000000010ec3d584 _ZN2CA11Transaction6commitEv + 608
    15  QuartzCore                          0x000000010ec3dede _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 76
    16  CoreFoundation                      0x000000010e1800f7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    17  CoreFoundation                      0x000000010e17a5be __CFRunLoopDoObservers + 430
    18  CoreFoundation                      0x000000010e17ac31 __CFRunLoopRun + 1505
    19  CoreFoundation                      0x000000010e17a302 CFRunLoopRunSpecific + 626
    20  GraphicsServices                    0x00000001112542fe GSEventRunModal + 65
    21  UIKitCore                           0x0000000115ce1ba2 UIApplicationMain + 140
    22  Ride Sharing App                    0x0000000108ac21ab main + 75
    23  libdyld.dylib                       0x000000010ca4c541 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

1 个答案:

答案 0 :(得分:-1)

您的问题可能是因为您没有设置委托和数据源。

所以试试这个: 在您的课程中:

class LocationSearchTable: UITableViewController, UITableViewDelegate, UITableViewDataSource {

//Then set the delegate and dataSource in ViewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self
   }

}

还要确保您的TableView商店名为tableView