我想使用Core Data在Swift中创建登录和注册功能。
这是我将数据存储在signupVC中的代码;
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext
let newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject
newUser.setValue(txtUsername.text, forKey: "username")
newUser.setValue(txtPassword.text, forKey: "password")
newUser.setValue(txtEmailAdd.text, forKey: "email")
do {
try context.save()
} catch {}
print(newUser)
print("Object Saved.")
这是LoginVC中的代码;
@IBAction func signinTapp(sender: UIButton) {
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext
let request = NSFetchRequest(entityName: "Users")
request.returnsObjectsAsFaults = false
request.predicate = NSPredicate(format: "username = %@", "" + txtUsername.text!)
let results:NSArray = try! context.executeFetchRequest(request)
if(results.count > 1){
let res = results[0] as! NSManagedObject
txtUsername.text = res.valueForKey("username") as! String
txtPassword.text = res.valueForKey("password") as! String
//for res in results {
// print(res)
}else{
print("Incorrect username and password")
}
}
任何人都可以告诉我最好的前进方向吗? - 我只需要检索已保存的核心数据并检查它是否匹配。
这是我的核心数据模型:
答案 0 :(得分:1)
查看以下代码
func CheckForUserNameAndPasswordMatch (userName : String, password : String) ->Bool
{
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var managedObjectContext = appDelegate.managedObjectContext
var predicate = NSPredicate (format:"userName = %@" ,userName)
var fetchRequest = NSFetchRequest ( entityName: "UserEntity")
fetchRequest.predicate = predicate
var error : NSError? = nil
var fetchRecult = managedObjectContext?.executeFetchRequest(fetchRequest, error: &error)
if fetchRecult?.count>0
{
var objectEntity : UserEntity = fetchRecult?.first as! UserEntity
if objectEntity.userName == userName && objectEntity.password == password
{
return true // Entered Username & password matched
}
else
{
return false //Wrong password/username
}
}
else
{
return false
}
}
如果您正在处理任何企业产品,那么在设备中保存密码并不好。
答案 1 :(得分:0)
根据数据库约束,username
是唯一的吗?然后,你将永远不会从获取中获得多个结果。
如果您使用
if let user = results.first where
user.pass == (passField.text ?? "") {
// login
}
else {
// no login
}
你会更好。
另外,不要从数据库中设置字段;检查它们是否相等。
此外,请注意,此类注册仅对每个应用安装有效。
对于生产安全性,只存储密码哈希值。
答案 2 :(得分:0)
导入UIKit 导入CoreData
类ViewController:UIViewController,UITextFieldDelegate {
@IBOutlet var txt_username: UITextField!
@IBOutlet var txt_password: UITextField!
var result = NSArray()
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 Log_in(_ sender: Any)
{
if txt_username.text == "" && txt_password.text == ""
{
let alert = UIAlertController(title: "Information", message: "Please enter all the fields", preferredStyle: .alert)
let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addAction(ok)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
else
{
self.CheckForUserNameAndPasswordMatch(username : txt_username.text! as String, password : txt_password.text! as String)
}
}
func CheckForUserNameAndPasswordMatch( username: String, password : String)
{
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
let fetchrequest = NSFetchRequest<NSFetchRequestResult>(entityName: "LoginDetails")
let predicate = NSPredicate(format: "username = %@", username)
fetchrequest.predicate = predicate
do
{
result = try context.fetch(fetchrequest) as NSArray
if result.count>0
{
let objectentity = result.firstObject as! LoginDetails
if objectentity.username == username && objectentity.password == password
{
print("Login Succesfully")
}
else
{
print("Wrong username or password !!!")
}
}
}
catch
{
let fetch_error = error as NSError
print("error", fetch_error.localizedDescription)
}
}
}
注册页面 ==================&GT;
导入UIKit 导入CoreData
类RegistrationPage:UIViewController,UITextFieldDelegate {
@IBOutlet var txt_user: UITextField!
@IBOutlet var txt_mailid: UITextField!
@IBOutlet var txt_pwd: UITextField!
@IBOutlet var txt_cpwd: UITextField!
@IBOutlet var txt_phone: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func register(_ sender: Any)
{
if txt_user.text == "" || txt_mailid.text == "" || txt_pwd.text == "" || txt_cpwd.text == "" || txt_phone.text == ""
{
let alert = UIAlertController(title: "Information", message: "Its Mandatort to enter all the fields", preferredStyle: .alert)
let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addAction(ok)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
else if (txt_pwd.text != txt_cpwd.text)
{
let alert = UIAlertController(title: "Information", message: "Password does not match", preferredStyle: .alert
)
let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addAction(ok)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
else
{
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
let new_user = NSEntityDescription.insertNewObject(forEntityName: "LoginDetails", into: context)
new_user.setValue(txt_user.text, forKey: "username")
new_user.setValue(txt_mailid.text, forKey: "mailid")
new_user.setValue(txt_pwd.text, forKey: "password")
new_user.setValue(txt_phone.text, forKey: "phone")
do
{
try context.save()
print("Registered Sucessfully")
}
catch
{
let Fetcherror = error as NSError
print("error", Fetcherror.localizedDescription)
}
}
self.navigationController?.popViewController(animated: true)
}
}
答案 3 :(得分:0)
使用核心数据制作用户登录系统非常简单
首先,您必须创建一个项目并在其中包含核心数据。然后,您必须将.xcdatamodeld文件添加到具有某些属性的实体。 这是一个文件如何显示的图片:
以下是示例代码:
from tkinter import *
def say_hi(name):
print(name)
root = Tk()
menu = Menu(root)
root.config(menu=menu)
subjects_menu = Menu(menu)
menu.add_cascade(label="Subjects", menu=subjects_menu)
d = ["name1", "name2"]
for name in d:
subjects_menu.add_command(label=name, command=lambda:say_hi(name))
'''
this is also not working
name = "Math"
subjects_menu.add_command(label=name, command=lambda:say_hi(name))
name = "Physics"
subjects_menu.add_command(label=name, command=lambda:say_hi(name))
'''
root.mainloop()
答案 4 :(得分:0)
Coredata保存获取更新删除 ==================================&GT;
导入UIKit 导入CoreData
类ViewController:UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet var my_table: UITableView!
var playerdata = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool)
{
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
let fetch_data = NSFetchRequest<NSManagedObject>(entityName: "PlayerDetails")
do
{
self.playerdata = try context.fetch(fetch_data as! NSFetchRequest<NSFetchRequestResult>) as! NSMutableArray
}
catch let error as NSError
{
print(error.localizedDescription)
}
self.my_table.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return playerdata.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = my_table.dequeueReusableCell(withIdentifier: "hari") as! TableViewCell123
let playerdetails = self.playerdata[indexPath.row]
cell.playername.text = (playerdetails as AnyObject) .value(forKey: "player_name")as? String
cell.playerid.text = (playerdetails as AnyObject) .value(forKey: "player_id")as? String
cell.playerteam.text = (playerdetails as AnyObject) .value(forKey: "player_team")as? String
cell.playerimage.image = UIImage(data: ((playerdetails as AnyObject) .value(forKey: "player_img")as? Data)!)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
self.performSegue(withIdentifier: "datapass", sender: self)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
if(editingStyle == .delete)
{
let user = self.playerdata[indexPath.row] as! NSManagedObject
context.delete(user)
do
{
try context.save()
self.playerdata.removeObject(at: indexPath.row)
my_table.deleteRows(at: [indexPath], with: .fade)
}
catch let error as NSError
{
print("error",error.localizedDescription)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "datapass"
{
let vc2 = segue.destination as! ViewController2
let index = my_table.indexPathForSelectedRow
let data = self.playerdata[(index?.row)!]
vc2.dataupdate = data as! NSManagedObject
}
}
}
VIEWCONTROLLER - 2 ===================&GT; 导入UIKit 导入CoreData
类ViewController2:UIViewController {
@IBOutlet var txt_playername: UITextField!
@IBOutlet var txt_playerid: UITextField!
@IBOutlet var txt_playerteam: UITextField!
@IBOutlet var img_playerimage: UIImageView!
var dataupdate = NSManagedObject()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if (dataupdate != nil)
{
txt_playername.text = dataupdate.value(forKey: "player_name")as? String
txt_playerid.text = dataupdate.value(forKey: "player_id")as? String
txt_playerteam.text = dataupdate.value(forKey: "player_team")as? String
img_playerimage.image = UIImage(data: dataupdate.value(forKey: "player_img") as! Data)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func save_update(_ sender: Any)
{
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
if (dataupdate != nil)
{
dataupdate.setValue(self.txt_playername.text, forKey: "player_name")
dataupdate.setValue(self.txt_playerid.text, forKey: "player_id")
dataupdate.setValue(self.txt_playerteam.text, forKey: "player_team")
let img_data = UIImageJPEGRepresentation(self.img_playerimage.image!, 1.0)
dataupdate.setValue(img_data, forKey: "player_img")
}
else
{
let newplayer = NSEntityDescription.insertNewObject(forEntityName: "PlayerDetails", into: context)
newplayer.setValue(self.txt_playername.text, forKey: "player_name")
newplayer.setValue(self.txt_playerid.text, forKey: "player_id")
newplayer.setValue(self.txt_playerteam.text, forKey: "player_team")
let img_data = UIImageJPEGRepresentation(self.img_playerimage.image!, 1.0)
newplayer.setValue(img_data, forKey: "player_img")
}
do
{
try context.save()
}
catch let error as NSError
{
print(error.localizedDescription)
}
self.dismiss(animated: true, completion: nil)
}
}