Search code examples
iosswiftuitableviewtwitter-fabricmopub

Using editActionsForRowAtIndexPath with MoPub on iOS


I'm using MoPub in my iOS app to display native adverts in a UITableView. I'm hitting an issue where I'm getting fatal error: Array index out of range errors and I understand why but I can't figure out how to fix it.

MoPub inserts rows into the UITableView and as a result, the indexPath parameter to editActionsForRowAtIndexPath includes the rows containing adverts. However, the array of data for the table does not include these rows and therefore for each advert that is inserted, the indexPath of the row showing the data is +1 when compared to the index in the data array for that row. See the editActionsForRowAtIndexPath method below.

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
    // fetch the data for the currently selected row
    let currentDictionary = xmlParser.arrParsedData[indexPath.row] as Dictionary<String, String>
    self.shareURL = currentDictionary["link"]!

    var shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "Share" , handler: { 
        (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in

        NSLog("indexPath:%d", indexPath.row)

    })

    return [shareAction]
}

For example, if I have an advert in the third row (index = 2), swiping on the non-MoPub advert rows, I get the following output:

indexPath:0
indexPath:1
indexPath:3
indexPath:4

So the MoPub advert is being counted in the indexPath parameter but since that row doesn't exist in my datasource array for the tableView, the indexPath parameters are now out of sync.

How can I make sure that the indexes of the data array and the rows of the table are kept in sync?


Solution

  • You can get the cell at the current indexPath within editActionsForRowAtIndexPath. With this cell, we can get the appropriate indexPath without including the ads indices with mp_indexPathForCell.

    Since editActionsForRowAtIndexPath takes in IndexPath, which is not the same when ads are included, we have to have a way to edit indexPath to the correct parameters.

    let cell = cellForRowAtIndexPath(indexPath)
    let indexPath = mp_indexPathForCell(cell)
    

    The above code replaces the indexPath with the modified indexPath without the ad indices included.