将项目添加到数组后,TableView不会更新

时间:2018-03-10 02:46:21

标签: swift tableview

我正在构建一个应用程序,它使用Twitter API发布到用户的Twitter并在TableView中加载这些推文。应用程序首次启动时,表格会正确加载。但是,在撰写和发布推文(确认推文已发布并在数组中)后,表视图仍然显示相同的推文,而不是新创建的推文。我认为它可能与异步代码有关,所以我在DispatchQueue函数中实现了refreshData()。表视图仍未加载最近添加的推文。如何更改refreshData()功能,以便在成功发布推文时更新表格?

import UIKit
import OAuthSwift

class FeedViewController: UIViewController,  UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate  {


    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tweetText: UITextField!

    var user: User!
    var tweets = [Tweet]()
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
        self.tableView.rowHeight = 200
        let consumerSecret = user.consumerSecret
        let consumerKey = user.consumerKey
        let oAuthToken = user.oAuthToken
        let oAuthSecret = user.oAuthSecret
        let oauthswift = user.oauthswift
        let screen_name = user.screen_name


        print("Feed Consumer Secret: \(consumerSecret)")
        print("Feed Consumer Key: \(consumerKey)")
        print("Feed Auth Token: \(oAuthToken)")
        print("Feed Auth Secret: \(oAuthSecret)")
        print("Screen Name: \(screen_name)")

        loadFeed(oauthswift: oauthswift)
        // Do any additional setup after loading the view.
    }

    @IBAction func postButtonPushed(_ sender: Any) {
        let oauthswift = user.oauthswift
        let url = "https://api.twitter.com/1.1/statuses/update.json?status="
        let tweet_url = tweetText.text
        let encoded_tweet = tweet_url?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)
        let new_url = url + encoded_tweet!
        let _ = oauthswift.client.post(
            new_url, parameters: [:],
            success: { response in
                let dataString = response.string!
                let jsonDict = try? response.jsonObject()
                let jsonDict2 = jsonDict as! Dictionary<String,Any>
                let tweetText2 = jsonDict2["text"]!
                let jsonDict4 = jsonDict2["user"] as! Dictionary<String,Any>
                let username = jsonDict4["screen_name"]!
                let newTweet = Tweet(tweetText: tweetText2 as! String, username: username as! String)
                self.tweets.append(newTweet)
                print(username)
                //print(dataString)
                self.loadFeed(oauthswift: oauthswift)
                self.tweetText.text = ""

        },
            failure: { error in
                print(error)
        }
        )
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let tweet = tweets[indexPath.row]

        if let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as? PostCell {
            cell.configureCell(tweet: tweet)
            return cell

        } else {
            return PostCell()
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tweets.count
    }

    func loadFeed(oauthswift: OAuth1Swift){
                print("LOAD FEED")
                let _ = oauthswift.client.get(
                    "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=\(user.screen_name)", parameters: [:],
                    success: { response in
                        let jsonDict = try? response.jsonObject()
                        let jsonDict2 = jsonDict as! Array<Dictionary<String,Any>>
                        let arrayCount = jsonDict2.count
                        for index in 0...arrayCount - 1 {
                            let jsonDict4 = jsonDict2[index]["user"] as! Dictionary<String,Any>
                            let tweetText = jsonDict2[index]["text"]!
                            let username = jsonDict4["screen_name"]!
                            let newTweet = Tweet(tweetText: tweetText as! String, username: username as! String)
                            self.tweets.append(newTweet)
                            print(tweetText)
                        }

                        self.refreshData()

                }, failure: { error in
                    print(error)
                }
                )

    }

    func refreshData() {
        DispatchQueue.main.async{
            self.tableView.reloadData()
        }
    }

}

PostCell.swift

import UIKit

class PostCell: UITableViewCell {
    @IBOutlet weak var userLabel: UILabel!
    @IBOutlet weak var tweetLabel: UILabel!

    var tweet: Tweet!

    func configureCell(tweet: Tweet) {

        self.userLabel.text = "@\(tweet.username)"
        self.tweetLabel.text = tweet.tweetText
        print(tweet.tweetText)

    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

1 个答案:

答案 0 :(得分:0)

由于您确定Twitter已接受该帖子并将新的Tweet附加到数据源,因此无需完整的reloadData。您可以仅在表中显示新行。

FeedViewController的方法postButtonPushed的{​​{1}}内,在此行oauthswift.client.post之后的self.tweets.append(newTweet)内部,添加以下内容:

DispatchQueue.main.async {
    self.tableView.beginUpdates()
    self.tableView.insertRows(at: [IndexPath(item: self.tweets.count-1, section: 0)],
                              with: .automatic)
    self.tableView.endUpdates()
}