我有两 (2) 个 swift 3.0 文件。
编辑:
我的目标是在登录成功后保持 ViewController 处于活动状态/出现。我想在点击注销按钮时保持 LoginVC 处于活动状态。
一切正常,例如发布和读取 json 数据。
编辑:
ViewController 在登录时成功激活,但是当我点击注销按钮时,停止并再次构建它,ViewController 仍然没有关闭。它应该重定向到 LoginVC。
我认为我的UserDefaults.standard代码可能有问题。
我的代码如下
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() { super.viewDidLoad() }
override func viewDidAppear(_ animated: Bool) {
let isUserLoggedIn = UserDefaults.standard.bool(forKey: "isUserLoggedIn")
if(!isUserLoggedIn){
self.performSegue(withIdentifier: "loginview", sender: self)
}
}
@IBAction func logoutData(_ sender: Any) {
UserDefaults.standard.set(true, forKey: "isUserLoggedIn");
UserDefaults.standard.synchronize();
self.performSegue(withIdentifier: "loginview", sender: self)
}
}
LoginVC.swift
import UIKit
class LoginVC: UIViewController {
@IBOutlet var _login: UITextField!
@IBOutlet var _pass: UITextField!
var login: String!
var pass: String!
override func viewDidLoad() { super.viewDidLoad() }
@IBAction func loginData(_ sender: Any) {
login = _login.text
pass = _pass.text
if(login == "" || pass == "") {
return
}
else {
let url = URL(string: "http://localhost/login.php")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"
let paramToLogin = "login=\(login!)&pass=\(pass!)"
request.httpBody = paramToLogin.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
if error != nil {
return
}
else {
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [String: String]
{
DispatchQueue.main.async {
let success = Int(json["message"]!)
if(success == 1){
UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
UserDefaults.standard.synchronize();
self.dismiss(animated: true, completion: nil)
return
}
}
}
}
catch { }
}
})
task.resume()
}
}
}