Login & Signup iOS Swift - Core Data -
i want create login , signup functions within swift using core data.
this code store data in signupvc;
let appdel:appdelegate = (uiapplication.sharedapplication().delegate as! appdelegate) let context:nsmanagedobjectcontext = appdel.managedobjectcontext let newuser = nsentitydescription.insertnewobjectforentityforname("users", inmanagedobjectcontext: context) nsmanagedobject newuser.setvalue(txtusername.text, forkey: "username") newuser.setvalue(txtpassword.text, forkey: "password") newuser.setvalue(txtemailadd.text, forkey: "email") { try context.save() } catch {} print(newuser) print("object saved.")
this code in 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 , password") } }
can please advise best way forward? - need retrieve saved core data , check if matches.
here core data model:
look below code
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 } }
moreover not save password in device if working on enterprise product.
Comments
Post a Comment