Search code examples
iosiphonexcodeswiftparse-platform

Parse Data on Koloda Library - can not display on view


Can someone please tell me what am I doing wrong? Probably a lot cos I am newbie, but looking forward to solve this!

I am using Koloda libray (https://github.com/Yalantis/Koloda/tree/networking_example) to fetch an Array of Objects into the Card so every card gets a row from my database. I have seen the networking exemple with Alamofire and tried my own code that implements Parse using the same exemple. It is getting the objects from Parse but I have not been able to display them into the cards. Weird, actually I have no errors and the console display "Successfully retrieved 5 objects", but this is only the loadData() function.

I am going to display a lot of text there from a nib!

What am I basically trying to achieve: I have (MyView.xib, MyView.swift) that provides the labels. (What I want, is to retrieve from the array to texts into the labels from xib)

I am retrieving the objects but I have not been successful on displaying them into the card:

Successfully retrieved 5 posts.
Optional("EvUICgRQ6E")
Optional("5kC0FLKQON")
Optional("1Uyxb2M1Et")
Optional("aeJpRCG7Qn")
Optional("GDmGh3IULm")

Some Errors: If I am returning the "numberOfCards" --- I am getting this error:

fatal error: Array index out of range
(lldb) 

If I return: "return UInt (self.data.count)" I am not getting any errors but the cards are not being displayed at all.

I am a bit of a newbie, but pointed into a good direction I will be able to get it done.

This is my ViewController.swift code:

    //
//  ViewController.swift
//  TinderCardsSwift
//
//  Created by Eugene Andreyev on 4/23/15.
//  Copyright (c) 2015 Eugene Andreyev. All rights reserved.
//

import UIKit
import Koloda
import pop
import Parse
import ParseUI

private var numberOfCards: UInt = 5

class ViewController: UIViewController, KolodaViewDataSource, KolodaViewDelegate {

    @IBOutlet weak var kolodaView: KolodaView!

    @IBOutlet weak var menuLeft: UIBarButtonItem!
    @IBOutlet weak var searchRight: UIBarButtonItem!

    var cardsCollection: [MyView] = []

    var labelText3 = ""
    var labelText4 = ""

    var currentObject:PFObject?

    override func viewDidLoad() {
        super.viewDidLoad()

        kolodaView.dataSource = self
        kolodaView.delegate = self

        menuLeft.target = self.revealViewController()
        menuLeft.action = Selector("revealToggle:")

        searchRight.target = self.revealViewController()
        searchRight.action = Selector("rightRevealToggle:")

        self.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal

        loadData()

    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!

    }


    //MARK: Geting Data From Parse and displaying 5 posts with a print result - WORKING
    func loadData (){

        if (!cardsCollection.isEmpty) {
            self.kolodaView.reloadData()
            return
        }

        let query = PFQuery(className:"Countries")
        query.orderByAscending("nameEnglish")
        query.findObjectsInBackgroundWithBlock {
            (objects:[PFObject]?, error:NSError?) -> Void in
            if error == nil {
                // The find succeeded.
                print("Successfully retrieved \(objects!.count) posts.")
                // Do something with the found objects
                if let objects = objects {
                    for object in objects {
                        let view = NSBundle.mainBundle().loadNibNamed("MyView", owner: self, options: nil)[0] as! MyView
                        view.label1.text = object["nameEnglish"] as? String
                        view.label2.text = object["capital"] as? String
                        self.cardsCollection += [view]
                        print(object.objectId)

                    }
                }
            } else {
                // Log details of the failure
                print("Error: \(error!) \(error!.userInfo)")
            }
        }
        self.kolodaView.reloadData()
        return
    }

    /*func printData () {

        let dataView = NSBundle.mainBundle().loadNibNamed("MyView",
            owner: self, options: nil)[0] as? MyView
        if let nameEnglish = object?["nameEnglish"] as? String {

            let lbl2 = dataView?.label1 as UILabel!
            lbl2!.text = nameEnglish




        }

        //return printData()
    }*/
    @IBAction func logOut4(sender: AnyObject) {

        // Send a request to log out a user
        PFUser.logOut()

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            let viewController:UIViewController = UIStoryboard(name: "SlideMain", bundle: nil).instantiateViewControllerWithIdentifier("Login_Platform")
            self.presentViewController(viewController, animated: true, completion: nil)


        })

    }

    override func viewWillAppear(animated: Bool) {

        if (PFUser.currentUser() == nil) {
            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                let viewController:UIViewController = UIStoryboard(name: "SlideMain", bundle: nil).instantiateViewControllerWithIdentifier("Login_Platform")
                self.presentViewController(viewController, animated: true, completion: nil)



            })
        }

    }


    //MARK: IBActions
    @IBAction func leftButtonTapped() {
        kolodaView?.swipe(SwipeResultDirection.Left)
    }

    @IBAction func rightButtonTapped() {
        kolodaView?.swipe(SwipeResultDirection.Right)
    }

    @IBAction func undoButtonTapped() {
        kolodaView?.revertAction()
    }

    //MARK: KolodaViewDataSource
    func kolodaNumberOfCards(koloda: KolodaView) -> UInt {
       return numberOfCards
        //return UInt (self.data.count)
        //return UInt(cardsCollection.count)

    }

    func kolodaViewForCardAtIndex(koloda: KolodaView, index: UInt) -> UIView {
        //return UIImageView(image: UIImage(named: "Card_like_\(index + 1)"))
        return (NSBundle.mainBundle().loadNibNamed("MyView",
        owner: self, options: nil)[0] as? MyView)!
        //let view = cardsCollection[Int(index)]
        //return view


       /* let dataView = NSBundle.mainBundle().loadNibNamed("MyView",
            owner: self, options: nil)[0] as? MyView
        let parseData = data[Int(index)]
        dataView?.label1?.text = parseData.labelText
        dataView?.label2?.text = parseData.label2Text

        return dataView!*/


    }
    func kolodaViewForCardOverlayAtIndex(koloda: KolodaView, index: UInt) -> OverlayView? {
        return NSBundle.mainBundle().loadNibNamed("OverlayView",
            owner: self, options: nil)[0] as? OverlayView
    }

    //MARK: KolodaViewDelegate

    func kolodaDidSwipedCardAtIndex(koloda: KolodaView, index: UInt, direction: SwipeResultDirection) {
        //Example: loading more cards
        if index >= 3 {
            numberOfCards = 5
            kolodaView.reloadData()
        }
    }

    func kolodaDidRunOutOfCards(koloda: KolodaView) {
        //Example: reloading
        kolodaView.resetCurrentCardNumber()
        loadData()
    }

    func kolodaDidSelectCardAtIndex(koloda: KolodaView, index: UInt) {
        UIApplication.sharedApplication().openURL(NSURL(string: "http://yalantis.com/")!)
    }

    func kolodaShouldApplyAppearAnimation(koloda: KolodaView) -> Bool {
        return true
    }

    func kolodaShouldMoveBackgroundCard(koloda: KolodaView) -> Bool {
        return true
    }

    func kolodaShouldTransparentizeNextCard(koloda: KolodaView) -> Bool {
        return true
    }

    func kolodaBackgroundCardAnimation(koloda: KolodaView) -> POPPropertyAnimation? {
        return nil
    }

}

This is MyView.swift (where I defined everything)

  //
//  MyView.swift
//
//
//  Created by Viorel Petrisor on 12/29/15.
//  Copyright © 2015 Viorel Petrisor. All rights reserved.
//

import UIKit

class MyView: UIView {

    @IBOutlet var label1: UILabel!
    @IBOutlet var label2: UILabel!
    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */

}

MyView has it's own nib. Gonna place some pictures with my project also:

KolodaView in my Main StoryBoard

Does anybody knows how to make this work? I have been struggling for 10 days now and still didn't get it to work.

I would deeply appreciate some help, hints!

UPDATE: I am now using this function for loadData()

func loadData (){

        if (!cardsCollection.isEmpty) {
            self.kolodaView.reloadData()
            return
        }

        let query = PFQuery(className:"Countries")
        query.orderByAscending("nameEnglish")
        query.findObjectsInBackgroundWithBlock {
            (objects:[PFObject]?, error:NSError?) -> Void in
            if error == nil {
                // The find succeeded.
                print("Successfully retrieved \(objects!.count) posts.")
                // Do something with the found objects
                if let objects = objects {
                    for object in objects {
                        let view = NSBundle.mainBundle().loadNibNamed("MyView", owner: self, options: nil)[0] as! MyView
                        view.label1.text = object["nameEnglish"] as? String
                        view.label2.text = object["capital"] as? String
                        self.cardsCollection += [view]
                        print(object.objectId)

                    }
                }
            } else {
                // Log details of the failure
                print("Error: \(error!) \(error!.userInfo)")
            }
        }
        self.kolodaView.reloadData()
        return
    }

WITH this variable

var cardsCollection: [MyView] = []

Solution

  • I had a similar issue with the Card not getting the data. Apparently, it was a problem with how I was calling the Bundle. Correct Swift 3.0 code below.

    func koloda(_ koloda: KolodaView, viewForCardAt index: Int) -> UIView {
    
        let bundle = Bundle(for: MyView.self) // This gets the correct bundle for your class, as sometimes you might have many bundles.
        let nib = UINib(nibName: String(describing: MyView.self), bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! MyView
    
        return view
    }