在IBAction swift之外获取更新变量

时间:2016-09-09 16:03:40

标签: ios swift uitableview

我很难找到如何获取更新facebookProfileUrl,以便我可以在单元格的imageview中放置图像。正如您在代码中看到的那样,我在页面顶部创建了一个var facebookProfileUrl实例。在代码的底部,你可以看到,如果facebookProfileUrl为空,它会这么说 - 这就是这段代码的作用。即使我在代码中间更改facebookProfileUrl,也没有任何反应。我该怎么做才能解决这个问题?

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)

                feedRef.setValue(feed.toAnyObject())

            }
            else
            {
                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
}

1 个答案:

答案 0 :(得分:0)

您应该在完成块中调用self.tableView.reloadData()(我建议将其作为if error == nil条件中的最后一行)

如上所述,这是一个异步调用,这意味着在服务器响应之后将调用该块req.startWithCompletionHandler({ ... })中的代码。到目前为止,tableView可能已经加载了它的数据(换句话说,已经为当前屏幕上的所有单元调用了cellForRowAtIndexPath)。

虽然小心!我不确定你要完成的是什么,我还没有看到你的所有代码,但是你这样做的方式,所有的单元格都会有相同的url。如果没有更多信息,建议更好的方法来做这件事很难,但要注意。

相关问题