为什么我的代码不起作用? - setObjectForKey:key不能为nil

时间:2016-06-27 21:08:41

标签: ios database swift uitableview firebase

处理我在Firebase上存储数据的应用,并将数据加载到我的TableView中。不得不从我发现的教程中稍微改变(旧)代码,所以我希望有人能发现我犯的错误。用户可以添加一个事件,其中包括:名称,日期,描述(所有字符串)和图像。这些数据被加载到TableView中的三个标签上。和图像在上面。

import UIKit
import Firebase
import FirebaseDatabaseUI

class EventViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    //outlets for text & image
    @IBOutlet weak var photoImageView: UIImageView!

    @IBOutlet weak var eventName: UITextField!
    @IBOutlet weak var eventDate: UITextField!
    @IBOutlet weak var eventDes: UITextView!

    //Database connection
    let rootref = FIRDatabase().reference()
    var imagePicker: UIImagePickerController = UIImagePickerController()



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

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

    @IBAction func submitEvent(sender: AnyObject) {

        let name = eventName.text
        let date = eventDate.text
        let text = eventDes.text
        var data: NSData = NSData()

        if let image = photoImageView.image {
            data = UIImageJPEGRepresentation(image,0.1)!
        }

        let base64String = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)

        let user: NSDictionary = ["name":name!, "date":date!, "text":text!, "photoBase64":base64String]

        //Add firebase child node
        let event = FIRDatabase().reference().child(name!)

        // Write data to Firebase
        event.setValue(user)

        navigationController?.popViewControllerAnimated(true)
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        view.endEditing(true)
        super.touchesBegan(touches, withEvent: event)
    }

    //UIImagePickerControllerDelegate methods

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        imagePicker.dismissViewControllerAnimated(true, completion: nil)
        photoImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
    }

    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        dismissViewControllerAnimated(true, completion: nil)
    }

    @IBAction func addPicture(sender: AnyObject) {
        if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) {
            imagePicker =  UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = .Camera

            presentViewController(imagePicker, animated: true, completion: nil)
        } else {
            imagePicker.allowsEditing = false
            imagePicker.sourceType = .PhotoLibrary
            imagePicker.delegate = self
            presentViewController(imagePicker, animated: true, completion:nil)
        }
    }
}

我的TABLEVIEWCONTROLLER

import UIKit
import Firebase

class EventTableViewController: UITableViewController {

    @IBOutlet weak var eventImage: UIImageView!
    @IBOutlet weak var eventName: UILabel!
    @IBOutlet weak var eventDate: UILabel!
    @IBOutlet weak var eventText: UITextView!

    let rootref = FIRDatabase().reference()
    var items = [NSDictionary]()


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

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        items = [NSDictionary]()

        FIRDatabase.load()
    }

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

    //TableView Data
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

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

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

        configureCell(cell, indexPath: indexPath)

        return cell
    }

    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {

            let dict = items[indexPath.row]
            let name = dict["name"] as! String

            // delete data from firebase

            let event = FIRDatabase().reference().child(name)
            event.removeValue()
        }
    }

    // MARK:- Configure Cell

    func configureCell(cell: UITableViewCell, indexPath: NSIndexPath) {
        let dict = items[indexPath.row]

        eventName.text = dict["name"] as? String
        eventDate.text = dict["name"] as? String
        eventText.text = dict["name"] as? String

        let base64String = dict["photoBase64"] as! String
        populateImage(cell, imageString: base64String)
    }

    func populateImage(cell:UITableViewCell, imageString: String) {

        let decodedData = NSData(base64EncodedString: imageString, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)

        let decodedImage = UIImage(data: decodedData!)

        cell.imageView!.image = decodedImage
    }

    //load data from Firebase
    func loadDataFromFirebase() {

        UIApplication.sharedApplication().networkActivityIndicatorVisible = true


            rootref.observeEventType(.Value, withBlock: { snapshot in
                var tempItems = [NSDictionary]()


            for item in snapshot.children {
                let child = item as! FIRDataSnapshot
                let dict = child.value as! NSDictionary
                tempItems.append(dict)
            }

            self.items = tempItems
            self.tableView.reloadData()
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false

        })
    }
}

获得我的工作想法的图像

My app so far

1 个答案:

答案 0 :(得分:2)

看看这一行:

let user: NSDictionary = ["name":name!, "date":date!, "text":text!, "photoBase64":base64String]

你在这里做了很多强制解缠。事实上,你在很多地方做了很多强制解缠。当你这样做时,你会说“我100%肯定这里总会有价值”。避免这几乎是所有成本。那条线应该是这样的。

if let unwrappedName = name , unwrappedDate = date, unwrappedText = text{
    let user: NSDictionary = ["name":unwrappedName, "date":unwrappedDate, "text":unwrappedText, "photoBase64":base64String]
}

解开这样的选项可以防止您的应用崩溃。你应该在这里放一个断点来看看什么值是零。每次使用一个!你应该仔细思考它。