Passando dados de um controlador de exibição para outro
Estou analisando dados com json e quero passar model_id para ActiveSubViewController / id_model. O que estou fazendo errado?
// 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)
}}
Veja o Controller que os dados precisam ser passados:
//
// 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
}
}