Calvin Orchiz Calvin Orchiz - 3 months ago 48
Swift Question

Parse Server // findObjectsInBackgroundWithBlock // Array

Parse Server: 2.2.17 (self hosted)

Parse-SDK-iOS-OSX: 1.14.2

ParseUI-iOS Version: 1.2.0

Xcode 7.3.1, Swift

I'm new at IOS Programming (20 weeks) and build an App for fun and learning.

I have a problem with a Parse function "findObjectsInBackgroundWithBlock" and array. After completing my function will give me an array with the initial values. Inside the function i can see the values added to the array.

class UserOverview {

var strings: [String] = ["1", "2", "3"]

init() {
userKcal()
}

func userKcal() -> [String] {
let query = PFQuery(className: "StringClassInParse")
query.whereKey("userPointer", equalTo: PFUser.currentUser()!)
query.findObjectsInBackgroundWithBlock { (objects, error) in
if let returnedObjects = objects {
for object in returnedObjects {
let kcal = object["kcal"] as? String
self.strings.append(kcal!)
}
}
print(self.strings) // output is ["1", "2", "3", "4", "5", "6"]
}
print(self.strings) // output is ["1", "2", "3"]
return strings
}


}

Any idea? + Sorry for this beginner question.

Answer

You need to use closures with your function because you are making block and block will work in async manner, so that you need to declare your function with closure and then return the String array with that closure.

func userKcal(completion: ([String]) -> ()) {
    let query = PFQuery(className: "StringClassInParse")
    query.whereKey("userPointer", equalTo: PFUser.currentUser()!)
    query.findObjectsInBackgroundWithBlock { (objects, error) in
        if let returnedObjects = objects {
            for object in returnedObjects {
                let kcal = object["kcal"] as? String
                self.strings.append(kcal!)
            }
        }
        completion(self.strings)
    }
}

Now call this function like this way

self.userKcal { (strings) -> () in
     print(strings)
}