senty
senty

Reputation: 12847

PFFile returning nil Optional Value - Swift 1.2

I have a problem on fetching Parse image files (PFFile).

   Usersclass { 
       var resultsUsernameArray = [String]() 
       var imageFiles = [PFFile]()
  }


  override func viewDidAppear(animated: Bool) {

    let predicate = NSPredicate(format: "username != '"+userName+"'")
    var query = PFQuery(className: "_User", predicate: predicate)


    if let objects = query.findObjects() {
        for object in objects {

            var user:PFUser = object as! PFUser
            self.resultsUsernameArray.append(user.username!)

            if object["photo"] != nil {

                self.imageFiles.append(object["photo"] as! PFFile)
               // this is where I get error

                self.resultsTable.reloadData()

            }
        }
    }

}

It used to work fine but with Swift 1.2, it seems like there is a problem. The error I am getting is: "Warning: A long-running operation is being executed on the main thread. Break on warnBlockingOperationOnMainThread() to debug. fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) "

Upvotes: 0

Views: 394

Answers (1)

BHendricks
BHendricks

Reputation: 4493

You're executing a fetch on the main queue, so I'm surprised this worked. The warning is telling you that you are trying to perform a long running operation on the main thread. You should change your findObjects() call to a call in the background, such as findObjectsInBackground, something like this:

query.findObjectsInBackgroundWithBlock({ (NSArray array, NSError error) -> Void in
    for object in objects {

        var user:PFUser = object as! PFUser
        self.resultsUsernameArray.append(user.username!)

        if object.objectForKey("photo") != nil {

            self.imageFiles.append(object.objectForKey("photo") as! PFFile)
           // this is where I get error

            self.resultsTable.reloadData()

        }
    }            
})

Upvotes: 0

Related Questions