如何从另一个View Controller更新UITableView?

时间:2016-10-23 17:34:00

标签: ios swift uitableview

我有一个场景:

ViewController1,ViewController显示“社区”的UITableView,并有一个按钮可以加入其他社区,从而加载另一个视图。

ViewController2,JoinCommunity有一个文本字段和一个连接按钮。

当用户输入正确的社区代码并单击“加入”时,会将用户注册到与代码匹配的社区中。此时JoinCommunity被解雇,ViewController出现。

我的问题是'ViewController'中的UITableView在用户注销并重新登录之前不会更新。

我被告知以下行应该实现它,但它没有,所以我仍然必须遗漏一些东西:

var communities = [String]() { didSet { communitiesTableView.reloadData()} }

这是ViewController的代码:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UsernameSentDelegate {

@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var receiveUsername: UILabel!
@IBOutlet weak var userEmailText: UILabel!
var userEmail: String?
var flag = false

var communities = [String]() { didSet { communitiesTableView.reloadData()
    }
}



@IBOutlet weak var communitiesTableView: UITableView!

@IBAction func unwindToHome(_ segue: UIStoryboardSegue) {


}


//recieves email address from delegate from LoginViewController
func userLoggedIn(data: String) {

  userEmailText.text = data
     }

override func viewDidLoad() {
    super.viewDidLoad()

    self.communitiesTableView.delegate = self
    self.communitiesTableView.dataSource = self

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return self.communities.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let title = self.communities[indexPath.row]

    let cell = UITableViewCell()

    cell.textLabel?.text = title

    return cell

}


override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    if segue.identifier == "loginView" {
        let loginViewController: LoginViewController = segue.destination as! LoginViewController
        loginViewController.delegate = self
    }

    if segue.identifier == "createCommunitySegue" {
        let createCommunityController: CreateNewCommunity = segue.destination as! CreateNewCommunity
        createCommunityController.myEmail = userEmailText.text
    }

    if segue.identifier == "joinCommunitySegue" {
        let joinCommunityController: JoinCommunity = segue.destination as! JoinCommunity
        joinCommunityController.myEmail = userEmailText.text
    }

}

     override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    if flag == true
    {
        print (flag)

        let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/getDetails.php?");
        var request = URLRequest(url:myUrl!);
        request.httpMethod = "POST";
        let postString = "email=\(userEmailText.text)";
        request.httpBody = postString.data(using: String.Encoding.utf8);

        let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

            DispatchQueue.main.async
                {

                    if error != nil {
                        print("error=\(error)")
                        return
                    }

                    do{
                        let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]

                        if let arr = json?["communities"] as? [[String:String]] {
                            self.communities = arr.flatMap { $0["name"]!

                        }

                    }



                    } catch{
                        print(error)
                    }
            }
        }
        task.resume()
    }
    self.communitiesTableView.delegate = self
    self.communitiesTableView.dataSource = self
    self.communitiesTableView.reloadData()
}

override func viewDidAppear(_ animated: Bool)
{

    communitiesTableView.reloadData()
   let isUserLoggedIn = UserDefaults.bool(UserDefaults.standard)(forKey: "isUserLoggedIn");

    if(!isUserLoggedIn)
    {
        self.performSegue(withIdentifier: "loginView", sender: self);
    }

}


}

这是JoinCommunity的代码:

import UIKit

class JoinCommunity: UIViewController {

@IBOutlet weak var communityCodeTextField: UITextField!

@IBAction func goBackTapped(_ sender: AnyObject) {
    self.performSegue(withIdentifier: "exitJoin", sender: self)
}
var myEmail: String?

@IBAction func joinCommunityTapped(_ sender: AnyObject) {

    let communityCode = communityCodeTextField.text;
    if (communityCode!.isEmpty){
        displayMyAlertMessage(userMessage: "You must enter Community code");

        return;
    }else{

        let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/joinCommunity.php?");

        var request = URLRequest(url:myUrl!);
        request.httpMethod = "POST";

        let postString = "code=\(communityCode!)&email=\(myEmail!)";

        request.httpBody = postString.data(using: String.Encoding.utf8);

        let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in


            DispatchQueue.main.async
                {


                    if error != nil {
                        print("error=\(error)")
                        return
                    }

                    do {

                        let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]


                        if let parseJSON = json {

                            let returnValue = parseJSON["status"] as? String

                            if( returnValue == "Success")
                            {
                                let myAlert = UIAlertController(title: "Alert", message: "Joined new community", preferredStyle: UIAlertControllerStyle.alert);


                                let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default){(action) in

                                    self.dismiss(animated: true, completion: nil)

                                }

                                myAlert.addAction(okAction);
                                self.present(myAlert, animated: true, completion: nil)

                            } else {


                                let errorMessage = parseJSON["message"] as? String
                                if(errorMessage != nil)
                                {

                                    self.displayMyAlertMessage(userMessage: errorMessage!);

                                }

                            }

                        }
                    } catch{
                        print(error)
                    }



            }

        }

        task.resume()


    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func displayMyAlertMessage(userMessage:String)
{
    let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);

    let okAction = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default, handler:nil);

    myAlert.addAction(okAction);

    self.present(myAlert, animated: true, completion: nil);


}

}

2 个答案:

答案 0 :(得分:0)

将JoinCommunity中的标志传递给最初设置为nil(可选类型)的ViewController,甚至布尔变量也可以。这可以通过prepareForSegue方法以及协议委托来实现。

UIViewController生命周期中的方法 viewWillAppear()每次推送UIViewController时都会执行,因为在导航堆栈中弹出了另一个UIViewController。所以基本上你只需要检查 viewWillAppear()中的标志是否已成功注册用户。

override func viewWillAppear()
{
    super.viewWillAppear()
    if flag == true
    {
        communitiesTableView.reloadData()
    }
}

用户可能会在注册一次后再次注册。因此,在UIViewController生命周期的 viewWillDisappear()方法中禁用此标志的原因是,如果用户实际上没有注册并弹出UIViewController,则会导致重新加载表。

如果要重新加载的数据来自某个API,您需要在UIViewController的生命周期中的 willViewAppear()方法中调用Web服务,并在收到后重新加载表响应。

如果多次重新加载数据没有问题,只需在viewWillAppear()中重新加载数据即可。 但这不是一个好的做法,因为它可以最大限度地减少应用程序的优化,因为每次重新加载数据而无需用户进行注册。

答案 1 :(得分:0)

浏览代码,ViewController,'社区'是用于填充TableView上数据的数组。用户在JoinCommunity Controller上成功加入社区。你只是解雇了控制器。社区' ViewController上的数组从未更新,因此显示旧数据。但是当用户注销并登录时,你说tableview会更新。我猜这是因为在登录时你得到了与用户相关的社区