I found a problem in your code - it findObjectsInBackgroundWithBlockis an asynchronous function, and the loop of your address array is called until completion findObjectsInBackgroundWithBlock. And since it is locationArrayempty at this point, the loop is not called.
, locationsSet , .
override func viewWillAppear(animated: Bool) {
let userlocation = PFUser.query()
PFGeoPoint.geoPointForCurrentLocationInBackground(){
(point:PFGeoPoint?, error:NSError?) -> Void in
NSLog("Test log 1")
if point != nil {
NSLog("Got current location successfully")
PFUser.currentUser()!.setValue(point, forKey: "userlocation")
PFUser.currentUser()!.saveInBackground()
}else{
NSLog("Failed to get current location")
}
var query = PFUser.query()
query?.whereKey("userlocation", nearGeoPoint: point!, withinMiles: 2.0)
query?.findObjectsInBackgroundWithBlock({ (objects: [AnyObject]?, error: NSError?) -> Void in
if(error == nil){
for object in objects! {
self.locationarray.append(object)
print(self.locationarray)
}
self.locationsSet()
}else{
print(error)
}
})
}
}
func locationsSet(){
for users in locationarray{
let button = UIButton()
button.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
button.frame = CGRectMake(100, 100, 100, 50)
let buttonWidth = button.frame.width
let buttonHeight = button.frame.height
let viewWidth = self.view.bounds.width
let viewHeight = self.view.bounds.height
let xwidth = viewWidth - buttonWidth
let yheight = viewHeight - buttonHeight
let xoffset = CGFloat(arc4random_uniform(UInt32(xwidth)))
let yoffset = CGFloat(arc4random_uniform(UInt32(yheight)))
button.center.x = xoffset + buttonWidth / 2
button.center.y = yoffset + buttonHeight / 2
self.userbutton.append(button)
print("called")
print(self.userbutton)
self.view.addSubview(button)
}
}