完成 ViewController 中的所有任务,然后跳转到 Xcode8 中的另一个 Swift 3

Complete all the task in a ViewController before jumping to another in Xcode8 Swift 3

所以,我仍在处理我的 poem 移动项目。我正在处理这个登录模块。这里发生的是它从一个 ViewController 跳到另一个 ViewController.. 也许是因为任务?有什么方法可以完成第一个ViewController中的所有任务,然后跳转到第二个ViewController(时间线ViewController)?如果第一个 ViewController 中的任务尚未完成,想阻止它进入时间线ViewController?

我希望有人能帮我解决这个问题.. :( 提前谢谢你!

这是我的ViewController代码

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var txtusername: UITextField!
    @IBOutlet weak var txtpassword: UITextField!
    @IBOutlet weak var lblResult: UILabel!
    var returnVal:String? = nil

    @IBOutlet weak var btnLogin: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

       @IBAction func btnLogin_Tapped(sender: UIButton) {

        let url:NSURL = NSURL(string: "http://192.168.1.6/Test/login.php")!
        let request:NSMutableURLRequest = NSMutableURLRequest(url:url as URL)
        let bodyData = "username=\(txtusername.text!)&password=\(txtpassword.text!)"

        request.httpMethod = "GET"
        request.httpBody = bodyData.data(using: String.Encoding.utf8);


      //  NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main){(response, data, error) in
            //print(response)
      //  }

        let task = URLSession.shared.dataTask(with: request as URLRequest)
        {
            data, response, error in

            guard let data = data, error == nil else {
                print ("Error = \(error?.localizedDescription ?? "Unknown error")")
                return
            }
            if let response = response {
                print ("Response = \(response)")
            }
            if let responseString = String(data: data, encoding: .utf8) {
                print ("Response data = \(responseString)")
            }

            //Converting response to NSDictionary
            guard let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments),
                let responseObject = json as? String,
                let returnValidation = responseObject as? String else {
                    print("did not validate")
                    return
            }

            DispatchQueue.main.async()
            {


                self.returnVal = returnValidation
                print("RETURN VALUE: \(self.returnVal!)")
                self.performSegue(withIdentifier: "signinSegue", sender: self)
            }
        }


        task.resume()


    }

    func AlertMessage(titleA: String, messageA: String)
    {
        let alert = UIAlertController(title: titleA, message: messageA, preferredStyle: UIAlertControllerStyle.alert)
        let alertAction = UIAlertAction(title: "Ok", style:UIAlertActionStyle.default){(UIAlertAction)-> Void in }
        alert.addAction(alertAction)
        present(alert,  animated: true){() -> Void in}
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if(segue.identifier == "signinSegue")
        {
            if(self.returnVal != nil)
            {

                if(self.returnVal! == "true")
                {
                let viewController = segue.destination as! TimelineViewController

                viewController.passedValue = self.returnVal!
                    viewController.viewDidLoad()

                }
                else if (self.returnVal! == "false")
                {
                    print("Incorrect Password!")
                }
            }
            else
            {
                print("Empty")
            }
        }
    }


}

这是我的时间轴ViewController代码

    import UIKit
    import Foundation

    struct Poem {
        let poemTitle: String
        let poemBody: String

        init?(dictionary: [String: Any]) {
            guard let poemTitle = dictionary["Title"] as? String,
                let poemBody = dictionary["Body"] as? String else {
                    print("Did not find fullName/Bio")
                    return nil
            }

            self.poemTitle = poemTitle
            self.poemBody = poemBody
        }
    }

    class TimelineViewController: UIViewController  {

        @IBOutlet weak var contentTableView: UITableView!
        @IBOutlet weak var poemBodyText: UITextView!
        @IBOutlet weak var poemTitleText: UILabel!

       var poems = [Poem]()
        var passedValue:String? = nil

        @IBOutlet weak var oPostBtn: UIButton!

        override func viewDidLoad() {
            super.viewDidLoad()

            if(passedValue != nil)
            {
                getPoems()
            }
            else {
                print("Empty")

            }

        }

        func getPoems()
        {
            let url = URL(string: "http://192.168.1.6/Test/feed1.php")!
            var request = URLRequest(url: url)

            request.httpMethod = "GET"


             let task = URLSession.shared.dataTask(with: request as URLRequest)
            {
                    data, response, error in

                    guard let data = data, error == nil else {
                        print("Error = \(error?.localizedDescription ?? "Unknown error")")
                        return
                    }
                    if let response = response {
                        print("Response = \(response)")
                    }
                    if let responseString = String(data: data, encoding: .utf8){
                        print ("Response data = \(responseString)")
                    }

                        //Converting response to NSDictionary
                        guard let json = try? JSONSerialization.jsonObject(with: data),
                    let responseObject = json as? [String:Any],
                            let returnPoems = responseObject["returnPoems"] as? [[String:Any]] else {
                                print ("Did not find return Poems")
                                return
                    }
                        print (returnPoems)

                    DispatchQueue.main.async {
                            self.poems = returnPoems.flatMap { Poem(dictionary: [=14=]) }
                            self.contentTableView.reloadData() }
            }
            task.resume()

        }

      /*  override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }*/
                   func AlertMessage(titleA: String, messageA: String)
            {
                let alert = UIAlertController(title: titleA, message: messageA, preferredStyle: UIAlertControllerStyle.alert)
                let alertAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default){(UIAlertAction)-> Void in }
                alert.addAction(alertAction)
                present(alert, animated: true){() -> Void in}
            }



        @IBAction func aPostBtn(_ sender: Any) {
            var count = 0
            while(count < 2)
            {
                //print("RESPONSE!!! : \(poemTitle[count])")
                count = count + 1;
            }

        }

    }

    extension TimelineViewController: UITableViewDelegate, UITableViewDataSource {


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

           guard let cell = contentTableView.dequeueReusableCell(withIdentifier: "PoemTableViewCell", for: indexPath) as? PoemTableViewCell else
           {
                fatalError("The dequeued cell is not an instance of PoemTableViewCell")
            }
            let poem = poems[indexPath.row]

            cell.poemTitleText?.text = poem.poemTitle
            cell.poemBodyText?.text = poem.poemBody


        //   cell.textLabel?.text = poem.poemTitle
         //   cell.detailTextLabel?.text = poem.poemBody

            return cell
        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return poems.count
        }
        func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
            print("You selected cell #\(indexPath.row)!")

           let poem = poems[indexPath.row]
            print(poem)

        }

    }

btnLogin_Tapped 中删除 DispatchQueue.main.async()。我不明白你为什么需要这个。它创建一个新队列并异步执行其中的代码。

也删除 viewController.viewDidLoad()。你不应该自己调用 viewDidLoad,它会在新视图控制器出现时自动调用。

另一件可能导致问题的事情是,如果您在 Storyboard 中创建了一个从登录按钮到 TimelineViewController 的 segue(Ctrl + 拖动)。您应该在 btnLogin_Tapped 末尾执行 segue 时将其删除。