Quickly update UITableView with new data

I am trying to overwrite my UITableViewdata from another JSON call.

However, my current setup does not seem to work, and although there are many similar questions on SO, the answers I could find I have already tried.

I save API data in object objects CoreData. And I populate my UITableView with my objects CoreData.

In my current setup, I have 3 different API calls that have different amounts of data and, of course, different values. I need to be able to switch between these 3 datasets and what I'm trying to do now. (still no progress).

I have a function called loadSuggestions where I assume that my error lies.

  • First I check my internet connection.

  • I set managedObjectContext

  • I check which API I need to call (this is determined before the function is called, and I checked that it works as intended)

  • I delete all current data from the object that it is trying to call. (I also tried deleting the data from the latest data uploaded UITableView. It didn't change anything). I also checked that this works. After deleting the data, I checked that it prints an empty array, I also tried to register the objects deleted by it to make sure.

  • Then I retrieve the new data, storing it in temporary variables. Then save it in my master data.

  • Then I make my second API call (depending on the variable from the first), retrieve this data and save it in the same way.

  • , UITableView . ( , )

  • , , tableView. ( )

:

func loadSuggestions() {
    println("----- Loading Data -----")
    // Check for an internet connection.
    if Reachability.isConnectedToNetwork() == false {
        println("ERROR: -> No Internet Connection <-")
    } else {
        // Set the managedContext again.
        managedContext = appDelegate.managedObjectContext!

        // Check what API to get the data from
        if Formula == 0 {
            formulaEntity = "TrialFormulaStock"
            println("Setting Entity: \(formulaEntity)")
            formulaAPI = NSURL(string: "http://api.com/json/entry_weekly.json")
        } else if Formula == 1 {
            formulaEntity = "ProFormulaStock"
            println("Setting Entity: \(formulaEntity)")
            formulaAPI = NSURL(string: "http://api.com/json/entry_weekly.json")
        } else if Formula == 2 {
            formulaEntity = "PremiumFormulaStock"
            formulaAPI = NSURL(string: "http://api.com/json/proff_weekly.json")
            println("Setting Entity: \(formulaEntity)")
        } else if Formula == 3 {
            formulaEntity = "PlatinumFormulaStock"
            println("Setting Entity: \(formulaEntity)")
            formulaAPI = NSURL(string: "http://api.com/json/fund_weekly.json")
        }

        // Delete all the current objects in the dataset
        let fetchRequest = NSFetchRequest(entityName: formulaEntity)
        let a = managedContext.executeFetchRequest(fetchRequest, error: nil) as! [NSManagedObject]
        for mo in a {
            managedContext.deleteObject(mo)
        }

        // Removing them from the array
        stocks.removeAll(keepCapacity: false)
        // Saving the now empty context.
        managedContext.save(nil)

        // Set up a fetch request for the API data
        let entity =  NSEntityDescription.entityForName(formulaEntity, inManagedObjectContext:managedContext)
        var request = NSURLRequest(URL: formulaAPI!)
        var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
        var formula = JSON(data: data!)

        // Loop through the api data.
        for (index: String, actionable: JSON) in formula["actionable"] {

            // Save the data into temporary variables
            stockName = actionable["name"].stringValue
            ticker = actionable["ticker"].stringValue
            action = actionable["action"].stringValue
            suggestedPrice = actionable["suggested_price"].floatValue
            weight = actionable["percentage_weight"].floatValue

            // Set up CoreData for inserting a new object.
            let stock = NSManagedObject(entity: entity!,insertIntoManagedObjectContext:managedContext)

            // Save the temporary variables into coreData
            stock.setValue(stockName, forKey: "name")
            stock.setValue(ticker, forKey: "ticker")
            stock.setValue(action, forKey: "action")
            stock.setValue(suggestedPrice, forKey: "suggestedPrice")
            stock.setValue(weight, forKey: "weight")

            // Get ready for second API call.
            var quoteAPI = NSURL(string: "http://dev.markitondemand.com/Api/v2/Quote/json?symbol=\(ticker)")

            // Second API fetch.
            var quoteRequest = NSURLRequest(URL: quoteAPI!)
            var quoteData = NSURLConnection.sendSynchronousRequest(quoteRequest, returningResponse: nil, error: nil)
            if quoteData != nil {
                // Save the data from second API call to temporary variables
                var quote = JSON(data: quoteData!)
                betterStockName = quote["Name"].stringValue
                lastPrice = quote["LastPrice"].floatValue

                // The second API call doesn't always find something, so checking if it exists is important.
                if betterStockName != "" {
                    stock.setValue(betterStockName, forKey: "name")
                }

                // This can simply be set, because it will be 0 if not found.
                stock.setValue(lastPrice, forKey: "lastPrice")

            } else {
                println("ERROR ----------------- NO DATA for \(ticker) --------------")
            }

            // Error handling
            var error: NSError?
            if !managedContext.save(&error) {
                println("Could not save \(error), \(error?.userInfo)")
            }
            // Append the object to the array. Which fills the UITableView
            stocks.append(stock)

        }

        // Reload the tableview with the new data.
        self.tableView.reloadData()
    }
}

, viewController, viewDidAppear :

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)

    tableView.allowsSelection = true
    if isFirstTime {
        loadSuggestions()
        isFirstTime = false
    }
}

View, , .

, , , :

func platinumFormulaTapGesture() {
    // Menu related actions
    selectView(platinumFormulaView)
    selectedMenuItem = 2
    // Setting the data to load
    Formula = 3
    // Sets the viewController. (this will mostly be the same ViewController)
    menuTabBarController.selectedIndex = 0
    // Set the new title
    navigationController?.navigationBar.topItem!.title = "PLATINUM FORMULA"
    // And here I call the loadSuggestions function again. (this does run)
    SuggestionsViewController().loadSuggestions()
}

tableView:

:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return stocks.count
}

cellForRowAtIndexPath ( CoreData)

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("com.mySuggestionsCell", forIndexPath: indexPath) as! mySuggestionsCell

    let formulaStock = stocks[indexPath.row]
    cell.stockNameLabel.text = formulaStock.valueForKey("name") as! String!
    cell.tickerLabel.text = formulaStock.valueForKey("ticker") as! String!
    action = formulaStock.valueForKey("action") as! String!
    suggestedPrice = formulaStock.valueForKey("suggestedPrice") as! Float

    let suggestedPriceString = "Suggested Price\n$\(suggestedPrice.roundTo(2))" as NSString
    var suggestedAttributedString = NSMutableAttributedString(string: suggestedPriceString as String)

    suggestedAttributedString.addAttributes(GrayLatoRegularAttribute, range: suggestedPriceString.rangeOfString("Suggested Price\n"))
    suggestedAttributedString.addAttributes(BlueHalisRBoldAttribute, range: suggestedPriceString.rangeOfString("$\(suggestedPrice.roundTo(2))"))
    cell.suggestedPriceLabel.attributedText = suggestedAttributedString

    if action == "SELL" {
        cell.suggestionContainer.backgroundColor = UIColor.formulaGreenColor()
    }

    if let lastPrice = formulaStock.valueForKey("lastPrice") as? Float {
        var lastPriceString = "Last Price\n$\(lastPrice.roundTo(2))" as NSString
        var lastAttributedString = NSMutableAttributedString(string: lastPriceString as String)

        lastAttributedString.addAttributes(GrayLatoRegularAttribute, range: lastPriceString.rangeOfString("Last Price\n"))

        percentDifference = ((lastPrice/suggestedPrice)*100.00)-100

        if percentDifference > 0 && action == "BUY" {
            lastAttributedString.addAttributes(RedHalisRBoldAttribute, range: lastPriceString.rangeOfString("$\(lastPrice.roundTo(2))"))
        } else if percentDifference <= 0 && percentDifference > -100 && action == "BUY" {
            lastAttributedString.addAttributes(GreenHalisRBoldAttribute, range: lastPriceString.rangeOfString("$\(lastPrice.roundTo(2))"))
        } else if percentDifference <= 0 && percentDifference > -100 && action == "SELL" {
            lastAttributedString.addAttributes(RedHalisRBoldAttribute, range: lastPriceString.rangeOfString("$\(lastPrice.roundTo(2))"))
        } else if percentDifference == -100 {
            lastPriceString = "Last Price\nN/A" as NSString
            lastAttributedString = NSMutableAttributedString(string: lastPriceString as String)

            lastAttributedString.addAttributes(GrayLatoRegularAttribute, range: lastPriceString.rangeOfString("Last Price\n"))
            lastAttributedString.addAttributes(BlackHalisRBoldAttribute, range: lastPriceString.rangeOfString("N/A"))
        }

        cell.lastPriceLabel.attributedText = lastAttributedString
    } else {
        println("lastPrice nil")
    }

    weight = formulaStock.valueForKey("weight") as! Float
    cell.circleChart.percentFill = weight
    let circleChartString = "\(weight.roundTo(2))%\nWEIGHT" as NSString
    var circleChartAttributedString = NSMutableAttributedString(string: circleChartString as String)
    circleChartAttributedString.addAttributes(BlueMediumHalisRBoldAttribute, range: circleChartString.rangeOfString("\(weight.roundTo(2))%\n"))
    circleChartAttributedString.addAttributes(BlackSmallHalisRBoldAttribute, range: circleChartString.rangeOfString("WEIGHT"))
    cell.circleChartLabel.attributedText = circleChartAttributedString

    cell.selectionStyle = UITableViewCellSelectionStyle.None
    return cell
}

appDelegate :

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var managedContext = NSManagedObjectContext()

, , . , loadSuggestions.

tableView, setNeedsDisplay setNeedsLayout self.view, tableView, , , .

, View , !

, .

+4
1

platinumFormulaTapGesture ,

SuggestionsViewController().loadSuggestions()

SuggestionsViewController, , . , . , , .

+2