Im trying to retrieve all the rows from a Parse server table that contains strings and images. Each one of those will then be mapped to a swift array and then used within the application. When I run this code, my append to array updates the count within the scope of the query block but once outside this block of code - I have an empty array as was initialized.
var langArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
let query = PFQuery(className:"Languages")
query.findObjectsInBackground { (objects, error) -> Void in
if error == nil {
for object in objects! {
self.langArray.append(object["name"] as! String)
print("inside this loop: \(self.langArray.count)")
}
} else {
print(error!)
}
print("outside the foreach loop: \(langArray.count)")
}
As per the code, Im running the query in the viewDidLoad() so it would be the first thing being retrieved.
So the problem you are running into is asynchronous calls. You are correct the viewDidLoad is the first thing called. The problem is that your query.findinbackgroundwithblock is a background task. This means the task will execute and finish whenever the network allows. The without the background task the code would usually run one line after another. This specific calls tells the device not to wait for it to finish before moving on. This is causing your "outside the for loop" println to be called before your loop even begins. When the data is returned from parseserver the code inside the query block will begin to execute. This allows you to print out the data in the array once it is populated. If you are trying to do something else with this code aside from just print you will need more of a code snip it. My suggestion is to create a method outside of viewDidLoad and then do some logic that causes the for loop to call the function when it hits the end of the loop.