NSFetchRequest could not locate an NSEntityDescription - xcode

I know this is a duplicate of other questions but I've followed the answers to those questions and I still get the same error.
I think the error is coming from the fact that the code is trying to fetch the data when it has not even been saved (there is a delay in saving the data because I am getting it from Parse). Any ideas?
The exact error I get is:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'NSFetchRequest could not locate an NSEntityDescription for entity name 'emailStatus''
-
import UIKit
import CoreData
class RegisterEmail: UIViewController {
var test1: Bool?
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func shouldPerformSegueWithIdentifier(identifier: String!, sender: AnyObject!) -> Bool {
if identifier == "passEmail" {
var query = PFUser.query()
query.getObjectInBackgroundWithId("vFu93HatwL") {
(User: PFObject!, error: NSError!) -> Void in
if error == nil {
NSLog("%#", User)
var checkEmail = User["emailVerified"] as Bool
println(checkEmail)
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var newEmail = NSEntityDescription.insertNewObjectForEntityForName("Email", inManagedObjectContext: context) as NSManagedObject
newEmail.setValue(checkEmail, forKey: "emailStatus")
context.save(nil)
println (newEmail)
println("Object Saved")
} else {
NSLog("%#", error)
}
}
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "emailStatus")
request.returnsObjectsAsFaults = false
var results: NSArray = context.executeFetchRequest(request, error: nil)!
if(results.count > 0)
{
var res = results [0] as NSManagedObject
test1 = res.valueForKey("emailStatus") as Bool
}
if (test1 == false) {
let alert = UIAlertView()
alert.title = "Error"
alert.message = "The email you have provided has not been verified."
alert.addButtonWithTitle("Dismiss")
alert.show()
return false
}
else {
return true
}
}
// by default, transition
return false
}
}

from op: "...everything is set up in the database file. Entity is called email and the attribute is emailStatus"
yet you try to fetch an entity emailStatus, where you likely want emails.
var request = NSFetchRequest(entityName: "emailStatus")
'typo'
fetch the right entity then: 'email'
var request = NSFetchRequest(entityName: "email")

Related

Parse.com - Download Objects From Database - Show Progress With ProgressBlock

I have Parse class called Product that has 238 rows. Note that this class is not the Parse.com implementation of Product, it is a custom class implemented by myself, as I didn't require all the columns Parse adds to their Product class.
The Product class has a Pointer column (basically a foreign key in SQL tables), called ShopId, because each product belongs to a specific Shop (I have a Parse class called Shop with an ObjectId column used in the Product Pointer.
My Product class also has a File column called imageFile that holds the image of the product.
I want to download all Products from a specific shop, unpackage their image file and put it in my Swift Product class which consists of the PFObject of the Parse Product, and a UIImageView and a UIImage. Here is my Product Class in Swift:
class Product {
private var object: PFObject
private var imageView: MMImageView!
private var image: UIImage
init(object: PFObject, image: UIImage) {
self.object = object
self.image = image
}
func getName() -> String {
if let name = object["name"] as? String {
return name
} else {
return "default"
}
}
func setImageView(size: CGFloat, target: DressingRoomViewController) {
self.imageView = MMImageView(frame:CGRectMake(0, 0, size, size))
imageView.contentMode = UIViewContentMode.ScaleAspectFit
imageView.image = self.image
imageView.setName(object["category"] as! String)
imageView.backgroundColor = UIColor.clearColor()
imageView.userInteractionEnabled = true
let tapGestureRecognizer =
UITapGestureRecognizer(target: target, action: "imageTapped:")
tapGestureRecognizer.numberOfTapsRequired = 1
imageView.addGestureRecognizer(tapGestureRecognizer)
}
func getImageView() -> MMImageView {
return self.imageView
}
}
I am currently downloading all the products just fine, and getting their image file and creating my Swift Products with their images. However my UIProgressView logic is slightly off. I have the UIProgressView running for every product, every time I unpackage the product image. I need to shift the Parse.com ProgressBlock out of the getProduct swift function and into the loadProducts #IBAction. When I try it, it causes a lot of errors before compilation. How do I shift the ProgressBlock up to the loadProducts #IBAction? Here is my current code:
//
// ChooseShopViewController.swift
// MirrorMirror
//
// Created by Ben on 12/09/15.
// Copyright (c) 2015 Amber. All rights reserved.
//
import UIKit
import Parse
class ChooseShopViewController: UIViewController {
var progressView: UIProgressView?
private var allProducts: [Product] = []
private var categories: [ProductCategory] = []
#IBAction func loadProducts(sender: AnyObject) {
let shopQuery = PFQuery(className:"Shop")
shopQuery.getObjectInBackgroundWithId("QjSbyC6k5C") {
(glamour: PFObject?, error: NSError?) -> Void in
if error == nil && glamour != nil {
let query = PFQuery(className:"Product")
query.whereKey("shopId", equalTo: glamour!)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
self.getAllProductsAndCategories(objects, error: error)
}
} else {
print(error)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Create Progress View Control
progressView = UIProgressView( progressViewStyle:
UIProgressViewStyle.Default)
progressView?.center = self.view.center
view.addSubview(progressView!)
}
override func prepareForSegue( segue: UIStoryboardSegue,
sender: AnyObject?) {
if (segue.identifier == "dressingRoom") {
ShopDisplay.sharedInstance.setAllProducts(self.allProducts)
ShopDisplay.sharedInstance.setAllProductCategories(self.categories)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func getAllProductsAndCategories(objects: [AnyObject]?, error: NSError?) {
if error == nil {
if let objects = objects as? [PFObject] {
for product in objects {
self.getCategory(product)
self.getProduct(product)
}
}
} else {
print("Error: \(error!) \(error!.userInfo)")
}
}
func getCategory(product: PFObject) {
if let category = product["category"] as? String {
var alreadyThere: Bool = false
for item in self.categories {
if category == item.rawValue {
alreadyThere = true
break
}
}
if alreadyThere == false {
self.categories.append(ProductCategory(rawValue: category)!)
}
}
}
func getProduct(product: PFObject) {
if let productImage = product["imageFile"] as? PFFile {
productImage.getDataInBackgroundWithBlock ({
(imageData: NSData?, error: NSError?) -> Void in
if let imageData = imageData {
let image = UIImage(data:imageData)
self.allProducts.append(
Product(object: product, image: image!))
}
if let downloadError = error {
print(downloadError.localizedDescription)
}
}, progressBlock: {
(percentDone: Int32) -> Void in
self.progressView?.progress = Float(percentDone)
if (percentDone == 100) {
//self.performSegueWithIdentifier("dressingRoom", sender: UIColor.greenColor())
}
})
}
}
}
I decided to not use the progressBlock, and instead to update my UIProgressView manually with a calculation. So here is the code. It's a little rusty. I could refactor now and maybe implement a calculated variable to make it cleaner. If my solution is a bad practice then I'm appreciative if that gets pointed out, and a better solution suggested (It doesn't seem good for performance to check the UIProgressView.progress value every iteration to perform the completion task of performing the segue).
import UIKit
import Parse
class ChooseShopViewController: UIViewController {
var progressView: UIProgressView?
private var allProducts: [Product] = []
private var categories: [ProductCategory] = []
static var numberOfProducts: Float = 0
#IBAction func loadProducts(sender: AnyObject) {
let shopQuery = PFQuery(className:"Shop")
shopQuery.getObjectInBackgroundWithId("QjSbyC6k5C") {
(glamour: PFObject?, error: NSError?) -> Void in
if error == nil && glamour != nil {
let query = PFQuery(className:"Product")
query.whereKey("shopId", equalTo: glamour!)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
ChooseShopViewController.numberOfProducts =
Float((objects?.count)!)
print(ChooseShopViewController.numberOfProducts)
self.getAllProductsAndCategories(objects, error: error)
}
} else {
print(error)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Create Progress View Control
progressView = UIProgressView( progressViewStyle:
UIProgressViewStyle.Default)
progressView?.center = self.view.center
progressView?.progress = 0.00
view.addSubview(progressView!)
}
override func prepareForSegue( segue: UIStoryboardSegue,
sender: AnyObject?) {
if (segue.identifier == "dressingRoom") {
ShopDisplay.sharedInstance.setAllProducts(self.allProducts)
ShopDisplay.sharedInstance.setAllProductCategories(self.categories)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func getAllProductsAndCategories(objects: [AnyObject]?, error: NSError?) {
if error == nil {
if let objects = objects as? [PFObject] {
for product in objects {
self.getCategory(product)
self.getProduct(product)
}
}
} else {
print("Error: \(error!) \(error!.userInfo)")
}
}
func getCategory(product: PFObject) {
if let category = product["category"] as? String {
var alreadyThere: Bool = false
for item in self.categories {
if category == item.rawValue {
alreadyThere = true
break
}
}
if alreadyThere == false {
self.categories.append(ProductCategory(rawValue: category)!)
}
}
}
func getProduct(product: PFObject) {
if let productImage = product["imageFile"] as? PFFile {
productImage.getDataInBackgroundWithBlock ({
(imageData: NSData?, error: NSError?) -> Void in
if let imageData = imageData {
let image = UIImage(data:imageData)
self.allProducts.append(
Product(object: product, image: image!))
self.progressView?.progress += (100.00 /
ChooseShopViewController.numberOfProducts) / 100.00
print(self.progressView?.progress)
if self.progressView?.progress == 1 {
self.performSegueWithIdentifier("dressingRoom",
sender: UIColor.greenColor())
}
}
if let downloadError = error {
print(downloadError.localizedDescription)
}
})
}
}
}
I found this on the Parse website. It may be useful as it has a block that shows the percentage done that updates regularly during the download!
let str = "Working at Parse is great!"
let data = str.dataUsingEncoding(NSUTF8StringEncoding)
let file = PFFile(name:"resume.txt", data:data)
file.saveInBackgroundWithBlock({
(succeeded: Bool, error: NSError?) -> Void in
// Handle success or failure here ...
}, progressBlock: {(percentDone: Int32) -> Void in
// Update your progress spinner here. percentDone will be between 0 and 100.
})
Did you find a better solution? besides this? I am trying to do something similar.

iOS 9(Swift 2.0): cannot invoke 'dataTaskwithURL' with an argument list of type '(NSURL, (_, _,_)throws -> Void)'

My app works perfectly fine with iOS 8 but yesterday I upgraded to iOS 9 and Xcode 7 then my app crashes. The error message is cannot invoke 'dataTaskwithURL' with an argument list of type '(NSURL, (_, ,)throws -> Void)'. I googled it and found a similar question here but the solution didn't really work (the solution was to add the do/catch blocks around the code). Can anyone help me with mine problem? Thank you!!!
Here's my code
import UIKit
import Foundation
import CoreLocation
class GoogleDataProvider {
let apiKey = "AIzaSyCQo-clIkek87N99RVh2lmFX9Mu9QPhAtA"
let serverKey = "AIzaSyBzmv7wPFcPAe1ucy5o6dqaXnda9i9MqjE"
var photoCache = [String:UIImage]()
var placesTask = NSURLSessionDataTask()
var session: NSURLSession {
return NSURLSession.sharedSession()
}
func fetchPlacesNearCoordinate(coordinate: CLLocationCoordinate2D, radius:Double, types:[String],keyword:String, completion: (([GooglePlace]) -> Void)) -> ()
{
var urlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=\(serverKey)&location=\(coordinate.latitude),\(coordinate.longitude)&radius=\(radius)&keyword=\(keyword)&rankby=prominence&sensor=true"
let typesString = types.count > 0 ? types.joinWithSeparator("|") : "food"
urlString += "&types=\(typesString)"
urlString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
if placesTask.taskIdentifier > 0 && placesTask.state == .Running {
placesTask.cancel()
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
do{
//******************Here's the line that displays error
placesTask = session.dataTaskWithURL(NSURL(string: urlString)!) {
(data, response, error) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
var placesArray = [GooglePlace]()
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? NSDictionary {
if let results = json["results"] as? NSArray {
for rawPlace:AnyObject in results {
let place = GooglePlace(dictionary: rawPlace as! NSDictionary, acceptedTypes: types)
placesArray.append(place)
if let reference = place.photoReference {
self.fetchPhotoFromReference(reference) { image in
place.photo = image
}
}
}
}
}
dispatch_async(dispatch_get_main_queue()) {
completion(placesArray)
}
}
}catch{
}
placesTask.resume()
}
func fetchDirectionsFrom(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D, completion: ((String?) -> Void)) -> ()
{
let urlString = "https://maps.googleapis.com/maps/api/directions/json?key=\(serverKey)&origin=\(from.latitude),\(from.longitude)&destination=\(to.latitude),\(to.longitude)&mode=walking"
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
do{
//******************************Here too ****************************
session.dataTaskWithURL(NSURL(string: urlString)!) {
(data, response, error) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
var encodedRoute: String?
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? [String:AnyObject] {
if let routes = json["routes"] as AnyObject? as? [AnyObject] {
if let route = routes.first as? [String : AnyObject] {
if let polyline = route["overview_polyline"] as AnyObject? as? [String : String] {
if let points = polyline["points"] as AnyObject? as? String {
encodedRoute = points
}
}
}
}
}
dispatch_async(dispatch_get_main_queue()) {
completion(encodedRoute)
}
}.resume()
}catch{
}
}
}
Sorry this is my first time posting the code style is a little bit confusing sorry about the indentation mess :)
Thanks again!!!
dataTaskWithURL:completionHandler: does not throw error.
Put do and catch inside dataTaskWithURL method.
for example:
session.dataTaskWithURL(NSURL(string: urlString)!) {
(data, response, error) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
var encodedRoute: String?
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? [String:AnyObject] {
if let routes = json["routes"] as AnyObject? as? [AnyObject] {
if let route = routes.first as? [String : AnyObject] {
if let polyline = route["overview_polyline"] as AnyObject? as? [String : String] {
if let points = polyline["points"] as AnyObject? as? String {
encodedRoute = points
}
}
}
}
}
} catch {
}
dispatch_async(dispatch_get_main_queue()) {
completion(encodedRoute)
}
}.resume()

Background music not working, but no errors?

Please solve my question, why is the background music not working? This is my code, hope someone can solve it.
// Just to format it..
#IBOutlet var UsernameTextField: UITextField!
#IBOutlet var PasswordTextField: UITextField!
#IBOutlet var EmailTextField: UITextField!
#IBAction func LogIn(sender: AnyObject) {
}
func Login(){
var user = PFUser()
user.username = UsernameTextField.text!
user.password = PasswordTextField.text!
PFUser.logInWithUsernameInBackground(UsernameTextField.text, password: PasswordTextField.text, block: {
(User : PFUser?, Error : NSError?) -> Void in
if Error == nil{
dispatch_sync(dispatch_get_main_queue()){
var Storyboard = UIStoryboard(name: "Main", bundle: nil)
var MainVC : UIViewController = Storyboard.instantiateViewControllerWithIdentifier("MainVC") as! UIViewController
self.presentViewController(MainVC, animated: true, completion: nil)
}
}
else{
NSLog("Sorry, you've typed either username or password wrongly.")
}
})
}
#IBAction func signUpButton(sender: AnyObject) {
signUp() // Calling signUp function here that is declared below.
}
func signUp(){
// Do sign up stuff.
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
playBackgroundMusic("IntroMusic")
backgroundMusicPlayer.play()
let soundFilePath = NSBundle.mainBundle().pathForResource("Background", ofType: "mp3")
let soundFileURL = NSURL(fileURLWithPath: soundFilePath!)
let player = AVAudioPlayer(contentsOfURL: soundFileURL, error: nil)
player.numberOfLoops = -1 //infinite
player.play()
func signUp(){
var user = PFUser()
user.username = UsernameTextField.text!
user.password = PasswordTextField.text!
user.email = EmailTextField.text!
}
let user = PFUser()
user.username = "Name:"
user.password = "Pass:"
user.email = "Email:"
user.signUpInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
if error == nil {
// Hooray! Let them use the app now.
} else {
// Examine the error object and inform the user.
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
var backgroundMusicPlayer: AVAudioPlayer!
func playBackgroundMusic(filename: String) {
//The location of the file and its type
let url = NSBundle.mainBundle().URLForResource("Background", withExtension: "mp3")
//Returns an error if it can't find the file name
if (url == nil) {
println("Could not find the file \(filename)")
}
var error: NSError? = nil
//Assigns the actual music to the music player
backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
//Error if it failed to create the music player
if backgroundMusicPlayer == nil {
println("Could not create audio player: \(error!)")
return
}
//A negative means it loops forever
backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
}
As Leo Dabus suggested declare your player instance outside of viewDidLoad method and your code will be:
var player : AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
let soundFilePath = NSBundle.mainBundle().pathForResource("Background", ofType: "mp3")
let soundFileURL = NSURL(fileURLWithPath: soundFilePath!)
player = AVAudioPlayer(contentsOfURL: soundFileURL, error: nil)
player.numberOfLoops = -1 //infinite
player.play()
}

Using xcode 6 and Swift, how can I grab all objectIds from a class on parse and put them into an array?

I am making a tiny quiz app to help my students study for tests. I have the questions on parse.com and successfully can query objects by their ID one at a time, but I end up having to hard code all the objectIds, and what I would like to do is grab the objectIds, put them into an array, and then pull a random question/objectID from that array as the students click through the questions.
I'm a novice, so ... while I may be able to understand the logic, I'm not sure how to write the code.
Here is the code I'm currently using ... but it doesn't include my failed attempts to put the object IDs in an array. I've been trying to add a function CallIDs() with a parse query to get them all, but so far ... no luck. Any ideas?
import UIKit
import Parse
class ViewController: UIViewController {
var ObjectIDs : [String]!
var Question : String!
var Answers : [String]!
var Answer : String!
#IBOutlet var QuestionLabel: UILabel!
#IBOutlet var Button1: UIButton!
#IBOutlet var Button2: UIButton!
#IBOutlet var Button3: UIButton!
#IBOutlet var Button4: UIButton!
#IBOutlet var AnswerResult: UILabel!
#IBOutlet var Next: UIButton!
#IBOutlet var QuizInstructions: UILabel!
var RandomID = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Hide()
CallData()
}
func GetRandomObjectID() {
ObjectIDs = ["jr92lfjbQc","r0C8oC4aJ6","XbTTX8xBRf","cjV2z4PSvV","wATbbu0JoX","9Y6HzfeeoD","mNHCMaao41","5qRcqyyXOL","JaLCoeyA1T","nrnifGOP1T","aDAQ6t3saJ","jKF0ZhmPxh"]
RandomID = Int (arc4random_uniform(UInt32(ObjectIDs.count)))
}
func CallData() {
GetRandomObjectID()
var query : PFQuery = PFQuery(className: "QuestionsandAnswers")
query.getObjectInBackgroundWithId(ObjectIDs[RandomID]) {
(ObjectHolder : PFObject!, error : NSError!) -> Void in
if (error == nil) {
self.Question = ObjectHolder ["Question"] as String!
self.Answers = ObjectHolder ["Answers"] as Array!
self.Answer = ObjectHolder ["Answer"] as String!
if (self.Answers.count > 0) {
self.QuestionLabel.text = self.Question
self.Button1.setTitle(self.Answers[0], forState: UIControlState.Normal)
self.Button2.setTitle(self.Answers[1], forState: UIControlState.Normal)
self.Button3.setTitle(self.Answers[2], forState: UIControlState.Normal)
self.Button4.setTitle(self.Answers[3], forState: UIControlState.Normal)
}
} else {
NSLog("Something is wrong, dude. Sorry.")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func Hide() {
AnswerResult.hidden = true
Next.hidden = true
}
func UnHide() {
AnswerResult.hidden = false
Next.hidden = false
}
#IBAction func Button1Action(sender: AnyObject) {
UnHide()
if (Answer == "0") {
AnswerResult.text = "Woot! That's correct!"
} else {
AnswerResult.text = "Nope. Try Again."
}
}
#IBAction func Button2Action(sender: AnyObject) {
UnHide()
if (Answer == "1") {
AnswerResult.text = "Woot! That's correct!"
} else {
AnswerResult.text = "Nope. Try Again."
}
}
#IBAction func Button3Action(sender: AnyObject) {
UnHide()
if (Answer == "2") {
AnswerResult.text = "Woot! That's correct!"
} else {
AnswerResult.text = "Nope. Try Again."
}
}
#IBAction func Button4Action(sender: AnyObject) {
UnHide()
if (Answer == "3") {
AnswerResult.text = "Woot! That's correct!"
} else {
AnswerResult.text = "Nope. Try Again."
}
}
#IBAction func Next(sender: AnyObject) {
CallData()
Hide()
}
}
///// well ... here is the function I attempted to code, but it isn't working:
func CallIDs() {
var query = PFQuery(className: “QuestionsandAnswers”) 
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in 
for object in objects {
self.objectIdsArray.append(object.objectId)
  }
}
}
I think the underlying misunderstanding in this question is that objects are to be retrieved using their ids. The requirement is for a random object, and that can be achieved better by knowing only the count of the objects stored on the server.
Getting the count we can select a random object by setting a random skip for a query. So, in the completion block of countObjectsInBackgroundWithBlock, get a random number up to that count like this:
let randomSkip = arc4random_uniform(count)
Now we're ready to do a query with no object id, setting query.skip = randomSkip, and query.limit = 1.
EDIT - If I were to build this in Objective-C, I would do it as follows:
- (void)randomQuestion:(void (^)(NSString *question, NSArray *answers))completion {
PFQuery *countQuery = [PFQuery queryWithClassName:#"QuestionsandAnswers"];
[countQuery countObjectsInBackgroundWithBlock:^(int count, NSError *error) {
NSInteger randomSkip = arc4random_uniform(count);
PFQuery *query = [PFQuery queryWithClassName:#"QuestionsandAnswers"];
query.skip = randomSkip;
query.limit = 1;
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
if (objects.count) {
PFObject *questionAndAnswerObject = objects[0];
NSString *question = questionAndAnswerObject[#"Question"];
NSArray *answers = questionAndAnswerObject[#"Answers"];
completion(question, answers);
} else {
NSLog(#"no error, but no Q&A objects found");
}
} else {
NSLog(#"there was an error %#", error);
completion(nil, nil);
}
}];
}];
}
I am not sure where you declare the array objectIdsArray. I was unable to find it. However the reason you may be having trouble replacing an existing array is because the function you are calling, findObjectsInBackgroundWithBlock does not run on the main thread. The code will continue to execute rather then waiting for the objectIds to download.
In order to make sure that you have downloaded the objectIds first before you try to use them, you may want to use the following code:
func CallIDs() {
var query = PFQuery(className: “QuestionsandAnswers”)
query.selectKeys(["objectId"])
self.objectIdsArray = query.findObjects()
}
Note: When run, you should see the following message:
Warning: A long-running operation is being executed on the main thread.
However I have not yet found this to be a problem. If the download is quick, it should not be noticeable. If it is taking a considerable amount of time, you can add in a UIActivityIndicatorView.

PFQuery not getting Object ID

The code below checks Parse to see if an email address has been verified. I am able to retrieve the object ID from Core Data (I saved it in a previous view controller) but when it comes to query.getObjectInBackgroundWithId(userID), userID is for some reason nil. I get the error:
Error: no results matched the query (Code: 101, Version: 1.6.0)
import UIKit
import CoreData
class HomePage: UIViewController{
#IBOutlet var emailMessage: UILabel!
//var userID: String!
override func viewDidLoad() {
super.viewDidLoad()
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Users")
request.returnsObjectsAsFaults = false
var results: NSArray = context.executeFetchRequest(request, error: nil)!
var res = results [0] as NSManagedObject
var userID = res.valueForKey("userID") as String
println (userID) //Correct ID is retrieved here
var query = PFQuery(className:"User")
query.getObjectInBackgroundWithId(userID) { //ID becomes nil
(email: PFObject!, error: NSError!) -> Void in
if error == nil {
let checkEmail = email["emailVerified"] as Bool
if (checkEmail != true)
{
self.emailMessage.hidden = false
}
else
{
self.emailMessage.hidden = true
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I think the problem lies in the way you're getting a PFQuery for the user. You should use the special user query:
var query = PFUser.query()
See Users - Querying, in the Parse docs.
The User table (as well as all other parse-managed classes) in parse is prefixed by underscore, so you should fix this line:
var query = PFQuery(className:"_User")

Resources