调用此函数并通过segue传递此数组的正确方法是什么?

时间:2016-10-22 10:09:55

标签: ios swift

我正在尝试使用segue将数组从loginViewController传递给ViewController

数组为communtiesArray,并在此部分代码中提取:

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

                if let arr = json?["communities"] as? [[String:String]] {
                    self.communitiesArray = arr.flatMap { $0["name"]! }
                }
               print ("first test: ",self.communitiesArray) // This prints values OK.

如上所述,此调试测试正确打印。我现在尝试在此函数中将communities.Array通过segue传递给ViewController:

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    if segue.identifier == "loginView" {
        let createViewController: ViewController = segue.destination as! ViewController
        createViewController.communities = communitiesArray
        print("second test: ", communitiesArray) //this prints nothing
    }    
}

我认为我在使用override func时一定出错,因为它似乎没有被调用,因为print调试没有激活。

这是完整的userLogin脚本:

import UIKit

protocol UsernameSentDelegate {
func userLoggedIn(data: String)
}

class LoginViewController: UIViewController {

var delegate: UsernameSentDelegate? = nil

@IBOutlet weak var userEmailTextField: UITextField!
@IBOutlet weak var userPasswordTextField: UITextField!
@IBOutlet weak var displayUserName: UILabel!
var communitiesArray  = [String]()


@IBAction func loginButtonTapped(_ sender: AnyObject)
{

    let userEmail = userEmailTextField.text;
    let userPassword = userPasswordTextField.text;

    if (userPassword!.isEmpty || userEmail!.isEmpty) { return; }

// send user data to server side

    let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/userLogin.php");
    var request = URLRequest(url:myUrl!);
    request.httpMethod = "POST";
    let postString = "email=\(userEmail!)&password=\(userPassword!)";
    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)
                {

                    //Display an alert message
                    let myAlert = UIAlertController(title: "Alert", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert);
                    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
                    myAlert.addAction(okAction);
                    self.present(myAlert, animated: true, completion: nil)
                    return
                }

                do {

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

                    if let arr = json?["communities"] as? [[String:String]] {
                        self.communitiesArray = arr.flatMap { $0["name"]! }
                    }
                   print ("first test: ",self.communitiesArray) // This print correctly in debug

                    // retrieve login details and check to see if all ok

                    if let parseJSON = json {

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

                        if(returnValue != "error")
                        {

                            self.delegate?.userLoggedIn(data: userEmail! )

                            UserDefaults.set(UserDefaults.standard)(true, forKey: "isUserLoggedIn");

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

                        } else {
                            // display an alert message
                            let userMessage = parseJSON["message"] as? 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)
                        }

                    }
                } catch
                {
                    print(error)
                }

        }

    }

    task.resume()

}


override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{

    if segue.identifier == "loginView" {
        let createViewController: ViewController = segue.destination as! ViewController
        createViewController.communities = communitiesArray
        print("second test: ", communitiesArray) //this prints nothing
    }

}


}

参考我在评论部分中所述的错误,这是来自ViewController的代码,其中包含第createViewController.communities = sender as? Array行的变量

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 communities = [String]() // this is the target of the segue

1 个答案:

答案 0 :(得分:0)

plz像这样执行segue

   performSegue(withIdentifier: "loginView", sender: self.communitiesArray)

并准备segue

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{

    if segue.identifier == "loginView" {
        let createViewController: ViewController = segue.destination as! ViewController
        createViewController.communities = sender as? Array

    }

}