简体   繁体   中英

No Data Fetched From Firebase in Cell In UiTableViewCell Swift 3

Hi guys i am stuck in a problem and couldnt find a solution anywhere .Can anyone tell me whats the issue, i have just started learning swift I want to fetch data from my firebase database and print it on the uitableviewcell

I have created a swift file which has

class Categories: NSObject { var categories : String? }

my Viewcontroller is below

import UIKit
import FirebaseDatabase


class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var categoryList = [Categories]()


    var refHandle:UInt!
    var ref:FIRDatabaseReference?

    @IBOutlet weak var listOfCategories: UITableView!
    @IBOutlet weak var menuBtn: UIBarButtonItem!


    override func viewDidLoad() {
        super.viewDidLoad()

        ref = FIRDatabase.database().reference()

        menuBtn.target = revealViewController()
        menuBtn.action = #selector(SWRevealViewController.revealToggle(_:))

        fetchCategories()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

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


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

        // Set cell content
        cell.textLabel?.text = categoryList[indexPath.row].categories

    return cell


    }

    func fetchCategories(){

        refHandle = ref?.child("Categories").observe(.childAdded, with: { (snapshot) in

            if let dictionary = snapshot.value as? [String: AnyObject] {

                print(dictionary)

                let categories = Categories()



                categories.setValuesForKeys(dictionary)
                self.categoryList.append(categories)

                DispatchQueue.main.async
                    {
                   self.listOfCategories.reloadData()
                }

            }
        })

    }


}

My Database

-Categories
  -name
    Bikes:"Bikes"
    Cars:"Cars"
    Cats:"Cats" 

if i print(categorList) i dont get it on the console too.. Below is the log

2017-04-06 06:09:50.531 Wallpapers App[1716] [Firebase/Analytics][I-ACS023007] Firebase Analytics v.3700000 started 2017-04-06 06:09:50.534 Wallpapers App[1716] [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see http://goo . gl/RfcP7r) 2017-04-06 06:09:50.565 Wallpapers App[1716] [Firebase/Analytics][I-ACS003007] Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist 2017-04-06 06:09:50.580 Wallpapers App[1716] [Firebase/Analytics][I-ACS005000] The AdSupport Framework is not currently linked. Some features will not function properly. Learn more at http://goo . gl/9vSsPb 2017-04-06 06:09:50.589 Wallpapers App[1716] [Firebase/Analytics][I-ACS023012] Firebase Analytics enabled ["Cars": Cars, "Bikes": Bikes, "Cats": Cats] 2017-04-06 06:09:52.565 Wallpapers App[1716:28745] * Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key Cars.' * First throw call stack: ( 0 CoreFoundation 0x0000000104725d4b exceptionPreprocess + 171 1 libobjc.A.dylib
0x0000000103d6621e objc_exception_throw + 48 2 CoreFoundation
0x0000000104725c99 -[NSException raise] + 9 3 Foundation
0x00000001038749df -[NSObject(NSKeyValueCoding) setValue:forKey:] + 291 4 Foundation 0x00000001038d672f -[NSObject(NSKeyValueCoding) setValuesForKeysWithDictionary:] + 301 5 Wallpapers App 0x00000001026fe886 _TFFC14Wallpapers_App14ViewController15fetchCategoriesFT_T_U_FCSo15FIRDataSnapshotT_ + 1126 6 Wallpapers App 0x00000001026fed8c _TTRXFo_oCSo15FIRDataSnapshot__XFdCb_dS_ + 60 7 Wallpapers App 0x00000001027c85b0 63-[FIRDatabaseQuery observeEventType:withBlock:withCancelBlock:]_block_invoke + 37 8
Wallpapers App 0x00000001027efeb3 __43-[FChildEventRegistration fireEvent:queue:]_block_invoke.68 + 88 9 libdispatch.dylib 0x0000000107470978 _dispatch_call_block_and_release + 12 10 libdispatch.dylib 0x000000010749a0cd _dispatch_client_callout + 8 11 libdispatch.dylib 0x000000010747a8a4 _dispatch_main_queue_callback_4CF + 406 12 CoreFoundation 0x00000001046e9e49 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE + 9 13 CoreFoundation 0x00000001046af37d __CFRunLoopRun + 2205 14 CoreFoundation 0x00000001046ae884 CFRunLoopRunSpecific + 420 15 GraphicsServices
0x0000000109439a6f GSEventRunModal + 161 16 UIKit
0x000000010525cc68 UIApplicationMain + 159 17 Wallpapers App
0x0000000102701fcf main + 111 18 libdyld.dylib
0x00000001074e668d start + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

You are using the method

setValuesForKeys

This method description says that:

Sets properties of the receiver with values from a given dictionary, using its keys to identify the properties.

And your error says, that your category class is not key-value compliant with the key "Cars", because there is no key/property named "Cars" in your "Categories" class.

From what I see, you are trying to print all these categories in a UITableViewCell. I would suggest changing your Categories class to the following:

struct Category() {
    var key: String
    var value: String
}

Post that, when you get the response in fetchCategories() method. Parse that dictionary:

for (key, value) in dictionary {
    let category = Category(key: key, value: value as! String)
    self.listOfCategories.append(category)
}

In your cellForRowAtIndexPath. You can set the text like so.

cell.textLabel?.text = categoryList[indexPath.row].value

You might want to simplify your Category struct if you just need the value in the response received from Firebase. Then your struct becomes a simple:

struct Category() {
    var name: String
}

I prefer using structs over classes wherever I can, but you can use a class if you really want.

Looks to me like you have two questions 1)showing the data in the cell 2)printing the data so you can see it

I'll address 2) as I think once you see the data, you can work with it (at least that has been my experience - also being fairly new to Xcode)

Xcode is not 'simple' to print the data like we'd like.... (you will probably find it as frustrating as I have - coming from a JS/jQuery/PHP background)

What I find simplest is to use a plugin called "SimpleJSON" (there are others, this is the one I found suits my purpose) and take the data to a JSON package, where I can see the data (the whole idea, right?), then work on it as needed from there.

in the pod file, just add

import SwiftyJSON

then in your code where you want to see the data

let categoriesJSON = JSON(categories)
print(categoriesJSON)

from there, you will get a list to work with in an array

print(categoriesJSON["name"]["Cars"]

Not a completely 'Swift-y' solution, perhaps, but it gets the job done!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM