facebook - Get data off completionhandler - FBRequestConnection -


i found lot of information concerning completionhandlers. however, don't yet how handle in case. maybe can me.

i'm trying list of facebook friends , store in array.

getfacebookfriends

func getfacebookfriends() -> nsmutablearray {      var retfriendids:nsmutablearray = []      fbrequestconnection.startformyfriendswithcompletionhandler {         (connection:fbrequestconnection!, result: anyobject!, error:nserror!) -> void in          if (error == nil){             var resultdict = result as! nsdictionary             self.data = resultdict.objectforkey("data") as! nsarray              var friendids:nsmutablearray = []             (var = 0; < self.data.count; i++) {                 let valuedict : nsdictionary = self.data[i] as! nsdictionary                 let id = valuedict.objectforkey("id") as! string                 friendids.addobject(id string)             }             retfriendids = friendids         }     }     return retfriendids } 

as completionhandler understand return fires before completion of block. how achieve return use list in function example?

findfacebookfriendsinbackend

func findfacebookfriendsinbackend() -> [anyobject]{     println("findfacebookfriendsinbackend")     var retfriends:[anyobject] = []      let fbfriends:nsmutablearray = getfacebookfriends()      var friendquery = pfuser.query()     // friends in parse     friendquery!.wherekey("fbid", containedin: fbfriends [anyobject])      friendquery!.findobjectsinbackgroundwithblock{         (friends, error) -> void in         if error == nil {             retfriends = friends [anyobject]!         }     }     return retfriends } 

and use in simple function this:

iterateoverfriends

func iterateoverfriends(friends:[anyobject]!){     in friends {         dosomething(i)     } } 

to call

iterateoverfriends(findfacebookfriendsinbackend()) 

short answer: don't. not possible. async method, result doesn't exist @ time when return.

you have adjust thinking.

rewrite method:

func findfacebookfriendsinbackend() -> [anyobject]{ 

as instead:

func findfacebookfriendsinbackend(#completion:   (friendsarray: [anyobject]) -> ()) 

in new form takes block parameter. write function invokes block once has built array of friends.

the new call this

findfacebookfriendsinbackend() {   (friendsarray) -> () in   iterateoverfriends(friendsarray) } 

(when have function takes closure final parameter, can call closure outside parenthesis.)

i wrote long answer, including working example project, in this thread.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -