我正在用json解析数据,我想将model_id传递给ActiveSubViewController / id_model。我做错了什么?
//
// 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
}
}
查看需要传递数据的控制器:
$("#health").replaceWith(originalState.clone(true));
答案 0 :(得分:0)
请使用此更新代码。
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)
}}
第二个ViewController
//
// 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
}
}
答案 1 :(得分:0)
在您的课程开头创建一个单独的属性var model_id:String =“”,然后使用prepare
函数之外的LoginBtnTapped
函数:
这是:
// 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!
}
}
}
}
答案 2 :(得分:-1)
在AppDelegate中创建字符串变量
var Model_id = String()
并且您获得用户名和userid的值将其值发送到AppDelegate。使appDelgate对象如下所示,并在destinationViewController
中相同let appDelegate = UIApplication.shared.delegate as! AppDelegate
将值传递给app委托变量
self.appDelegate. Model_id = "your Value"
并获取您想要获取的值,如下所示
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let string = appDelegate. Model_id as! String