D. Finna D. Finna - 1 year ago 65
Swift Question

Getting updated variable outside IBAction swift

I am having a hard time, finding out how to get the updates

so that I can put an image in my imageview in the cell. As you can see in the code I have made an instance with the var facebookProfileUrl at the top of my page. At the bottom of the code, you can see that if facebookProfileUrl is empty, it will say so - and that's what this code is doing. Even though I am changing facebookProfileUrl in the middle of the code, nothing happens. What can I do to fix this?

var facebookProfileUrl = "" // THIS IS BEFORE viewDidLoad

@IBAction func addToFeed(sender: AnyObject) {
let accessToken = FBSDKAccessToken.currentAccessToken()
if(accessToken != nil) //should be != nil
let req = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id"], tokenString: accessToken.tokenString, version: nil, HTTPMethod: "GET")
req.startWithCompletionHandler({ (connection, result, error : NSError!) -> Void in
if(error == nil)
let userId: String? = result.valueForKey("id") as? String
let userID = userId
self.facebookProfileUrl = "http://graph.facebook.com/\(userID)/picture?type=large" // HERE I AM CHANGING THE VARIABLE

let feed = Sweet(content: feedContent, addedByUser: name!, profilePhoto: self.facebookProfileUrl)
let feedRef = self.dbRef.child(feedContent.lowercaseString)


print("error \(error)")

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:updateTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! updateTableViewCell

let update = updates[indexPath.row]

cell.nameLabel.text = update.addedByUser
cell.updateLabel.text = update.content

if (facebookProfileUrl != "") {
if let url = NSURL(string: facebookProfileUrl) {
if let data = NSData(contentsOfURL: url) {
cell.picView.image = UIImage(data: data)
} else {
print("Empty facebookProfileUrl") // THIS ONE IS PRINTED

return cell

Answer Source

You should call self.tableView.reloadData() in the completion block (I'd recommend as the last line in the if error == nil condition)

As mentioned above, this is an asynchronous call, meaning that the code within that block req.startWithCompletionHandler({ ... }) will be called AFTER the server responds. By this point, it's likely that the tableView has already loaded its data (in other words cellForRowAtIndexPath has been called for all cells currently on the screen).

Be careful though! I'm not sure exactly what you're trying to accomplish and I haven't seen all of your code, but the way you doing this, all cells will have the same url. It's tough to recommend a better way to do this without more information, but beware.