【问题标题】:Passing data from one view controller to another将数据从一个视图控制器传递到另一个视图控制器
【发布时间】:2017-07-03 03:23:42
【问题描述】:

我正在使用 json 解析数据,我想将 model_id 传递给 ActiveSubViewController / id_model。我做错了什么?

//  ViewController.swift
//
//  Copyright © 2017 smokzz. All rights reserved.
//

import UIKit
import SwiftMessages
import Alamofire



class ViewController: UIViewController,UIAlertViewDelegate {

    @IBOutlet var myTableView: UIView!
    @IBOutlet weak var EmailField: UITextField!
    @IBOutlet weak var PasswordField: UITextField!


    @IBAction func LoginBtnTapped(_ sender: Any) {

        let userEmail = EmailField.text!
        let userPassword = PasswordField.text!



        if((userEmail.isEmpty) || (userPassword.isEmpty)){

//            createAlert(title: "Oops! ", message: "Email or Password field is empty")

            let view = MessageView.viewFromNib(layout: .CardView)
            view.configureTheme(.error)
            view.configureDropShadow()
            let iconText = ["????"].sm_random()!
            view.configureContent(title: "Oops!", body: "Email or Password field is empty.", iconText: iconText)
            SwiftMessages.show(view: view)
            if #available(iOS 10.0, *) {
                let PhoneVibrate = UINotificationFeedbackGenerator()
                PhoneVibrate.notificationOccurred(.error)

            }

            return

            }


        else {

            let myUrl = URL(string: "http://192.168.0.105/api/api.php?action=login");

            var request = URLRequest(url:myUrl!)

            request.httpMethod = "POST"// Compose a query string

            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

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

                // You can print out response object
                print("response = \(response)")

                //Let's convert response sent from a server side script to a NSDictionary object:
                do {
                    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                    if let parseJSON = json {

                        // Now we can access value of First Name by its key
                        let Message = parseJSON["status"] as? String
                        var model_id = parseJSON["id"] as? String
                        print("Message: \(Message)")
                        print("Model ID: \(model_id)")

                        if(Message == "true"){



                            let view = MessageView.viewFromNib(layout: .CardView)
                            view.configureTheme(.success)
                            view.configureDropShadow()
                            let iconText = ["????????"].sm_random()!
                            view.configureContent(title: "Welcome!", body: "You have successfully logged in.", iconText: iconText)
                            SwiftMessages.show(view: view)


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

                                    if let destination = segue.destination as? ActiveSubViewController {
                                        destination.id_model = model_id!
                                    }


                            }



                                OperationQueue.main.addOperation {
                                self.dismiss(animated: true, completion: nil);
                                self.performSegue(withIdentifier: "Home", sender: self)
                            }
                        }

                        else
                        {

                            let view = MessageView.viewFromNib(layout: .CardView)
                            view.configureTheme(.warning)
                            view.configureDropShadow()
                            let iconText = ["????"].sm_random()!
                            view.configureContent(title: "Sorry!", body: "Incorrect Email or Password.", iconText: iconText)
                            SwiftMessages.show(view: view)

                        }


                    }
                } catch {
                    print(error)
                }
            }
            task.resume()


        }


    }

    override func viewDidLoad() {
        super.viewDidLoad()


        //dissmis keyboard
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")

        view.addGestureRecognizer(tap)
    }

    func dismissKeyboard() {
        view.endEditing(true)
    }



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

    func createAlert(title:String, message:String)

    {
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
          alert.dismiss(animated: true, completion: nil)
        }))
        self.present(alert, animated: true, completion: nil)
    }}

需要传递数据的ViewController:

    //
//  ActiveSubViewController.swift
//  
//
//
//

import UIKit

class ActiveSubViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {


    var FetchedActiveUsers = [Active_Snaps]()

    @IBOutlet var label: UILabel!

    var id_model = String()

    @IBOutlet weak var TableViewActiveSnaps: UITableView!



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

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



        let cell = TableViewActiveSnaps.dequeueReusableCell(withIdentifier: "ActiveSnaps")

        cell?.textLabel?.text = FetchedActiveUsers[indexPath.row].snap_user
        cell?.detailTextLabel?.text = FetchedActiveUsers[indexPath.row].snap_date

        return cell!

    }



    override func viewDidLoad() {

        super.viewDidLoad()

        TableViewActiveSnaps.dataSource = self

        ParseActiveSnaps()


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

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

    func ParseActiveSnaps() {

        FetchedActiveUsers = []
        print("ID: \(id_model)")
        let url = "http://192.168.0.105/api/v2/public/api/customer/\(id_model)"
        var request = URLRequest(url: URL(string: url)!)
        request.httpMethod = "GET"
        let configuration = URLSessionConfiguration.default
        let session =  URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
        let task = session.dataTask(with: request) { (data, response, error) in

            if (error != nil) {
                print("Error!")
            } else {
                do {
                    let FetchetData = try JSONSerialization.jsonObject(with:  data!, options: .mutableLeaves) as! NSArray

                    for eachFetchedActiveUsers in FetchetData {

                        let eachActivesnap = eachFetchedActiveUsers as! [String : Any]
                        let snap_user = eachActivesnap["active"] as! String
                        let snap_date = eachActivesnap["date"] as! String


                        self.FetchedActiveUsers.append(Active_Snaps(snap_user: snap_user, snap_date: snap_date))

                    }
                    self.TableViewActiveSnaps.reloadData()
                }
                catch{
                    print("Erorr 2")
                }
            }

        }
        task.resume()



    }


    }


class Active_Snaps {

    var snap_user : String
    var snap_date : String

    init(snap_user : String, snap_date : String) {
        self.snap_user = snap_user
        self.snap_date = snap_date
    }

}

【问题讨论】:

  • 让destination = segue.destination 为? ActiveSubViewController {destination.id_model = model_id! } 尝试从那里删除 if 并检查是否在值传递时发生控制?
  • @iOSGeek 我收到此错误截图:prntscr.com/fqwyvl
  • 如果是这种情况,只需使用应用委托来传递数据我应该展示一个演示吗?
  • @iOSGeek 是的,我刚开始在 swift 上编码,所以我不太了解:/
  • 请查看我的回答

标签: json swift swift3


【解决方案1】:

在您的 AppDelegate Like 中创建字符串变量

var Model_id = String()

并且您在哪里获取用户名和用户 ID 的值将其值发送到 AppDelegate。使 AppDelgate 对象如下所示,并且在 destinationViewController 中相同

let appDelegate = UIApplication.shared.delegate as! AppDelegate

将值传递给应用委托变量

self.appDelegate. Model_id = "your Value"

并在您想要获取的任何地方获取您的值,如下所示

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let  string = appDelegate. Model_id as! String

【讨论】:

  • 屏幕截图:prntscr.com/fqx3ta我可以通过电子邮件将这个项目发送给您,以便您修复它吗?
  • 告诉我您是如何在 appDelegate 中创建变量的。您是否按照我的步骤操作?
  • 您是在目标屏幕中直接访问 Appdelegate 吗?
  • 在目标屏幕让 appDelegate = UIApplication.shared.delegate as! AppDelegate 然后让 string = appDelegate.model_id
  • 我在 AppDelegate.swift 中添加了这个“var model_id = String()”这个“让 appDelegate = UIApplication.shared.delegate as!AppDelegate appDelegate.model_id = model_id!”在 ViewController.swift 和 ActiveSubViewController.swift 中的“让 id_model = AppDelegate.model_id as!String”
【解决方案2】:

请使用此更新后的代码。

    import UIKit
    import SwiftMessages
    import Alamofire



    class ViewController: UIViewController,UIAlertViewDelegate {

        @IBOutlet var myTableView: UIView!
        @IBOutlet weak var EmailField: UITextField!
        @IBOutlet weak var PasswordField: UITextField!

        var model_id = ""

        @IBAction func LoginBtnTapped(_ sender: Any) {

            let userEmail = EmailField.text!
            let userPassword = PasswordField.text!



            if((userEmail.isEmpty) || (userPassword.isEmpty)){

                //            createAlert(title: "Oops! ", message: "Email or Password field is empty")

                let view = MessageView.viewFromNib(layout: .CardView)
                view.configureTheme(.error)
                view.configureDropShadow()
                let iconText = ["?"].sm_random()!
                view.configureContent(title: "Oops!", body: "Email or Password field is empty.", iconText: iconText)
                SwiftMessages.show(view: view)
                if #available(iOS 10.0, *) {
                    let PhoneVibrate = UINotificationFeedbackGenerator()
                    PhoneVibrate.notificationOccurred(.error)

                }

                return

            }


            else {

                let myUrl = URL(string: "http://192.168.0.105/api/api.php?action=login");

                var request = URLRequest(url:myUrl!)

                request.httpMethod = "POST"// Compose a query string

                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

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

                    // You can print out response object
                    print("response = \(response)")

                    //Let's convert response sent from a server side script to a NSDictionary object:
                    do {
                        let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                        if let parseJSON = json {

                            // Now we can access value of First Name by its key
                            let Message = parseJSON["status"] as? String
                             model_id = parseJSON["id"] as? String
                            print("Message: \(Message)")
                            print("Model ID: \(model_id)")

                            if(Message == "true"){



                                let view = MessageView.viewFromNib(layout: .CardView)
                                view.configureTheme(.success)
                                view.configureDropShadow()
                                let iconText = ["??"].sm_random()!
                                view.configureContent(title: "Welcome!", body: "You have successfully logged in.", iconText: iconText)
                                SwiftMessages.show(view: view)


    //                            func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    //                                
    //                                if let destination = segue.destination as? ActiveSubViewController {
    //                                    destination.id_model = model_id!
    //                                }
    //                                
    //                                
    //                            }
    //                            
                                let nextView  = (self.storyboard?.instantiateViewController(withIdentifier: "ActiveSubViewController"))! as! ActiveSubViewController
                                nextView.id_model = model_id!
                               self.navigationController?.pushViewController(nextView, animated: true)

    //                            OperationQueue.main.addOperation {
    //                                self.dismiss(animated: true, completion: nil);
    //                                self.performSegue(withIdentifier: "Home", sender: self)
    //                            }
                            }

                            else
                            {

                                let view = MessageView.viewFromNib(layout: .CardView)
                                view.configureTheme(.warning)
                                view.configureDropShadow()
                                let iconText = ["?"].sm_random()!
                                view.configureContent(title: "Sorry!", body: "Incorrect Email or Password.", iconText: iconText)
                                SwiftMessages.show(view: view)

                            }


                        }
                    } catch {
                        print(error)
                    }
                }
                task.resume()


            }


        }

        override func viewDidLoad() {
            super.viewDidLoad()


            //dissmis keyboard
            let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")

            view.addGestureRecognizer(tap)
        }

        func dismissKeyboard() {
            view.endEditing(true)
        }



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

        func createAlert(title:String, message:String)

        {
            let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
                alert.dismiss(animated: true, completion: nil)
            }))
            self.present(alert, animated: true, completion: nil)
        }}

第二个视图控制器

    //
//  ActiveSubViewController.swift
//
//
//
//

import UIKit

class ActiveSubViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {


    var FetchedActiveUsers = [Active_Snaps]()

    @IBOutlet var label: UILabel!

    var id_model = ""

    @IBOutlet weak var TableViewActiveSnaps: UITableView!



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

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



        let cell = TableViewActiveSnaps.dequeueReusableCell(withIdentifier: "ActiveSnaps")

        cell?.textLabel?.text = FetchedActiveUsers[indexPath.row].snap_user
        cell?.detailTextLabel?.text = FetchedActiveUsers[indexPath.row].snap_date

        return cell!

    }



    override func viewDidLoad() {

        super.viewDidLoad()

        TableViewActiveSnaps.dataSource = self

        ParseActiveSnaps()


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

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

    func ParseActiveSnaps() {

        FetchedActiveUsers = []
        print("ID: \(id_model)")
        let url = "http://192.168.0.105/api/v2/public/api/customer/\(id_model)"
        var request = URLRequest(url: URL(string: url)!)
        request.httpMethod = "GET"
        let configuration = URLSessionConfiguration.default
        let session =  URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
        let task = session.dataTask(with: request) { (data, response, error) in

            if (error != nil) {
                print("Error!")
            } else {
                do {
                    let FetchetData = try JSONSerialization.jsonObject(with:  data!, options: .mutableLeaves) as! NSArray

                    for eachFetchedActiveUsers in FetchetData {

                        let eachActivesnap = eachFetchedActiveUsers as! [String : Any]
                        let snap_user = eachActivesnap["active"] as! String
                        let snap_date = eachActivesnap["date"] as! String


                        self.FetchedActiveUsers.append(Active_Snaps(snap_user: snap_user, snap_date: snap_date))

                    }
                    self.TableViewActiveSnaps.reloadData()
                }
                catch{
                    print("Erorr 2")
                }
            }

        }
        task.resume()



    }


}


class Active_Snaps {

    var snap_user : String
    var snap_date : String

    init(snap_user : String, snap_date : String) {
        self.snap_user = snap_user
        self.snap_date = snap_date
    }

}

【讨论】:

  • 它不工作,现在它不能进入​​第二个视图控制器!
  • 在 Storyboard 中设置标识符 ActiveSubViewController 第二个视图控制器。
【解决方案3】:

在类的开头创建一个单独的属性 var model_id : String = "" 然后在 LoginBtnTapped 函数之外使用 prepare 函数:

这里是:

      //  ViewController.swift
    //
    //  Copyright © 2017 smokzz. All rights reserved.
    //

    import UIKit
    import SwiftMessages
    import Alamofire



    class ViewController: UIViewController,UIAlertViewDelegate {

        @IBOutlet var myTableView: UIView!
        @IBOutlet weak var EmailField: UITextField!
        @IBOutlet weak var PasswordField: UITextField!

         var model_id : String = ""

        @IBAction func LoginBtnTapped(_ sender: Any) {

            let userEmail = EmailField.text!
            let userPassword = PasswordField.text!



            if((userEmail.isEmpty) || (userPassword.isEmpty)){

    //            createAlert(title: "Oops! ", message: "Email or Password field is empty")

                let view = MessageView.viewFromNib(layout: .CardView)
                view.configureTheme(.error)
                view.configureDropShadow()
                let iconText = ["?"].sm_random()!
                view.configureContent(title: "Oops!", body: "Email or Password field is empty.", iconText: iconText)
                SwiftMessages.show(view: view)
                if #available(iOS 10.0, *) {
                    let PhoneVibrate = UINotificationFeedbackGenerator()
                    PhoneVibrate.notificationOccurred(.error)

                }

                return

                }


            else {

                let myUrl = URL(string: "http://192.168.0.105/api/api.php?action=login");

                var request = URLRequest(url:myUrl!)

                request.httpMethod = "POST"// Compose a query string

                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

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

                    // You can print out response object
                    print("response = \(response)")

                    //Let's convert response sent from a server side script to a NSDictionary object:
                    do {
                        let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                        if let parseJSON = json {

                            // Now we can access value of First Name by its key
                            let Message = parseJSON["status"] as? String
                            model_id = parseJSON["id"] as? String
                            print("Message: \(Message)")
                            print("Model ID: \(model_id)")

                            if(Message == "true"){



                                let view = MessageView.viewFromNib(layout: .CardView)
                                view.configureTheme(.success)
                                view.configureDropShadow()
                                let iconText = ["??"].sm_random()!
                                view.configureContent(title: "Welcome!", body: "You have successfully logged in.", iconText: iconText)
                                SwiftMessages.show(view: view)



                                    OperationQueue.main.addOperation {
                                    self.dismiss(animated: true, completion: nil);
                                    self.performSegue(withIdentifier: "Home", sender: self)
                                }
                            }

                            else
                            {

                                let view = MessageView.viewFromNib(layout: .CardView)
                                view.configureTheme(.warning)
                                view.configureDropShadow()
                                let iconText = ["?"].sm_random()!
                                view.configureContent(title: "Sorry!", body: "Incorrect Email or Password.", iconText: iconText)
                                SwiftMessages.show(view: view)

                            }


                        }
                    } catch {
                        print(error)
                    }
                }
                task.resume()


            }


        }

        override func viewDidLoad() {
            super.viewDidLoad()


            //dissmis keyboard
            let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")

            view.addGestureRecognizer(tap)
        }

        func dismissKeyboard() {
            view.endEditing(true)
        }



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

        func createAlert(title:String, message:String)

        {
            let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
              alert.dismiss(animated: true, completion: nil)
            }))
            self.present(alert, animated: true, completion: nil)
        }
  override func prepare(for segue: UIStoryboardSegue, sender: Any?) 
{
    if segue.identifier == "Home" {
            if let destination = segue.destination as? ActiveSubViewController {
                 destination.id_model = model_id!
            }
        }

 }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    • 2020-09-22
    相关资源
    最近更新 更多