Search code examples
iosswiftfatal-errordispatch-asyncoptional-values

unexpectedly found nil while unwrapping an Optional value dispatch-async


I am trying to implement loading data from Parse server after tapping a button on postVC to load data and navigate to guestVC. It was working fine and at some point began to crash the app...not sure why? I am getting the fatal error: unexpectedly found nil while unwrapping an Optional value...Any and all direction or help would be greatly appreciated. Thanks!

import UIKit
import Parse

var postuuid = [String]()

class postVC: UITableViewController {

//postVC button click function
//clicked username button from post
    @IBAction func usernameBtn_click(sender: AnyObject) {
        let i = sender.layer.valueForKey("index") as! NSIndexPath
        let cell = tableView.cellForRowAtIndexPath(i) as! postCell

        // if user tapped on himself go home, else go guest
        if cell.usernameBtn.titleLabel?.text == PFUser.currentUser()?.username {
            let home = self.storyboard?.instantiateViewControllerWithIdentifier("homeVC") as! homeVC
            self.navigationController?.pushViewController(home, animated: true)    
        } else {
            let guest = self.storyboard?.instantiateViewControllerWithIdentifier("guestVC") as! guestVC
            self.navigationController?.pushViewController(guest, animated: true)
        }  
    } 



// guestVC relevant code
import UIKit
import Parse

var guestname = [String]()

class guestVC: UICollectionViewController {

    var uuidArray = [String]()
    var picArray = [PFFile]()

    // posts loading function
    func loadPosts() {     

            let query = PFQuery(className: "posts")
// app keeps crashing in line below when I try to load data to guestVC
            query.whereKey("username", equalTo: guestname.last!)
            query.limit = self.page
            query.findObjectsInBackgroundWithBlock( { (objects:[PFObject]?, error:NSError?) -> Void in

                if error == nil {

                    self.uuidArray.removeAll(keepCapacity: false)
                    self.picArray.removeAll(keepCapacity: false)

                    for object in objects! {
                        self.uuidArray.append(object.valueForKey("uuid") as! String)
                        self.picArray.append(object.valueForKey("pic") as! PFFile)
                    }

                    self.collectionView?.reloadData()
                } else {
                    print(error!.localizedDescription)
                }
                dispatch_async(dispatch_get_main_queue(), { () -> Void in

                    // code here will be executed as the main queue

                })
            })

    }

Solution

  • You use a lot of exclamation marks to force unwrap optional values in your code, it's a bad habit. For example, you can unwrap guestname.last safely by:

    guard let lastItem = guestname.last else {
    // do something else
    return
    }
    query.whereKey("username", equalTo: lastItem)