簡體   English   中英

使用Swift和CoreData-用戶登錄

[英]Using Swift and CoreData - users logging in

因此,我正在創建一個iOS應用程序,並希望允許用戶登錄和注銷/注冊。 我正在使用核心數據執行此操作,當前我的程序允許用戶注冊,但數據並未保存,因此當他們嘗試登錄時,它說出錯誤的用戶名/密碼,換句話說,程序無法識別事實用戶在創建/注冊帳戶時已經輸入了他們的信息,因此無法加載他們輸入的信息,並且不允許用戶登錄。這是當用戶單擊注冊按鈕時需要的代碼-請救命:

import UIKit
import CoreData

class RegisterPageViewController: UIViewController {
    @IBOutlet weak var userEmailTextField: UITextField!
    @IBOutlet weak var userPasswordTextField: UITextField!
    @IBOutlet weak var confirmPasswordTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func registerButtonTapped(sender: AnyObject) {

    let userEmail = userEmailTextField.text
    let userPassword = userPasswordTextField.text
    let userConfirmPassword = confirmPasswordTextField.text

    if (userEmail.isEmpty || userPassword.isEmpty || userConfirmPassword.isEmpty) {

        displayMyAlertMessage("You haven't filled out all the fields.")
        return;

    }

    if (userPassword != userConfirmPassword) {

        displayMyAlertMessage("Passwords do not match.")
        return;


    }

    var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    var context:NSManagedObjectContext = appDel.managedObjectContext!

    var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject

    context.save(nil)



    var successAlert = UIAlertController(title: "Alert", message: "Successfully registered.", preferredStyle: UIAlertControllerStyle.Alert)
    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { action in
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    successAlert.addAction(okAction)
    self.presentViewController(successAlert, animated: true, completion: nil)





}




@IBAction func haveAnAccountButtonTapped(sender: AnyObject) {
    self.dismissViewControllerAnimated(true, completion: nil)
}




func displayMyAlertMessage(userMessage:String) {

    var alert = UIAlertController(title: "Alert!", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert)

    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)

    alert.addAction(okAction)

    self.presentViewController(alert, animated: true, completion: nil)
}





/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

如果您的* .xcdatamodel文件中已經具有屬性“ name”和“ password”的實體“ Users”,則需要存儲來自textField的數據,例如:

...
    var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject

    newUser.setValue(userEmail, forKey: "name")

    newUser.setValue(userPassword, forKey: "password")

    context.save(nil)
...

SWIFT 4

我們可以使用核心數據在Swift 4中創建登錄和注冊

在這里,我要使用Xcode 9在Swift 4中創建一個新項目,並為我提供示例性的核心數據任務

使用Select Use CoreData創建新項目

創建實體-用戶添加字段-名稱,年齡,密碼,電子郵件.... Plz選擇所有帶有String的字段類型

用適當的對象設計情節提要…。

創建登錄名,注冊,用戶詳細信息,注銷VC

導入CoreData以獲取適當的類

對於連接視圖,我們可以將StoryboardId和Segue用於視圖

創建LoginVc

import UIKit
import CoreData
class LoginViewController: UIViewController {

    @IBOutlet var nameTextCheck: UITextField!
    @IBOutlet var passwordTextCheck: UITextField!
    var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func signUPButtonAction(_ sender: Any) {
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
        let searchString = self.nameTextCheck.text
        let searcghstring2 = self.passwordTextCheck.text
        request.predicate = NSPredicate (format: "name == %@", searchString!)
        do
        {
            let result = try context.fetch(request)
            if result.count > 0
            {
                let   n = (result[0] as AnyObject).value(forKey: "name") as! String
                let p = (result[0] as AnyObject).value(forKey: "password") as! String
                //  print(" checking")


                if (searchString == n && searcghstring2 == p)
                {
                    let UserDetailsVc = self.storyboard?.instantiateViewController(withIdentifier: "UserDetailsViewController") as! UserDetailsViewController
                    UserDetailsVc.myStringValue = nameTextCheck.text
                    self.navigationController?.pushViewController(UserDetailsVc, animated: true)
                }
                else if (searchString == n || searcghstring2 == p)
                {
                    // print("password incorrect ")
                    let alertController1 = UIAlertController (title: "no user found ", message: "password incorrect ", preferredStyle: UIAlertControllerStyle.alert)
                    alertController1.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
                    present(alertController1, animated: true, completion: nil)
                }
            }
            else
            {
                let alertController1 = UIAlertController (title: "no user found ", message: "invalid username ", preferredStyle: UIAlertControllerStyle.alert)
                alertController1.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
                present(alertController1, animated: true, completion: nil)
                print("no user found")
            }
        }
        catch
        {
            print("error")
        }
    }
}

創建SignUpVc

import UIKit
import CoreData
class SignUpViewController: UIViewController {

    @IBOutlet var nameText: UITextField!
    @IBOutlet var passwordText: UITextField!
    @IBOutlet var ageText: UITextField!
    @IBOutlet var emailText: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
          }
      @IBAction func SignUPAction(_ sender: Any) {
        if isValidInput(Input: nameText.text!)
        {
            if isPasswordValid(passwordText.text!)
            {
                if isValidEmail(testStr: emailText.text!)
                {
                        let _:AppDelegate = (UIApplication.shared.delegate as! AppDelegate)
                        let context:NSManagedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
                            let newUser = NSEntityDescription.insertNewObject(forEntityName: "User", into: context) as NSManagedObject
                        newUser.setValue(nameText.text, forKey: "name")
                        newUser.setValue(passwordText.text, forKey: "password")
                        newUser.setValue(emailText.text, forKey: "email")
                        newUser.setValue(ageText.text, forKey: "age")
                        do {
                            try context.save()
                        } catch {}
                        print(newUser)
                        print("Object Saved.")
                       let alertController1 = UIAlertController (title: "Valid ", message: "Sucess ", preferredStyle: UIAlertControllerStyle.alert)
                        alertController1.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
                        present(alertController1, animated: true, completion: nil)


                        let UserDetailsVc = self.storyboard?.instantiateViewController(withIdentifier: "logoutViewController") as! logoutViewController

                        self.navigationController?.pushViewController(UserDetailsVc, animated: true)

                    }else
                {
                    print("mail check")
                    let alertController1 = UIAlertController (title: "Fill Email id", message: "Enter valid email", preferredStyle: UIAlertControllerStyle.alert)

                    alertController1.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
                    present(alertController1, animated: true, completion: nil)
                }
            }
            else
            {
                print("pswd check")
                let alertController1 = UIAlertController (title: "Fill the password ", message: "Enter valid password", preferredStyle: UIAlertControllerStyle.alert)
                alertController1.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
                present(alertController1, animated: true, completion: nil)
            }
        }
        else
        {
            print("name check")

            let alertController1 = UIAlertController (title: "Fill the Name ", message: "Enter valid username", preferredStyle: UIAlertControllerStyle.alert)

            alertController1.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            present(alertController1, animated: true, completion: nil)
        }
    }
        func isValidInput(Input:String) -> Bool
        {
        let RegEx = "\\A\\w{3,18}\\z"
        let Test = NSPredicate(format:"SELF MATCHES %@", RegEx)
        return Test.evaluate(with: Input)
        }
    func isPasswordValid(_ password : String) -> Bool{
        let passwordTest = NSPredicate(format: "SELF MATCHES %@", "^(?=.*[a-z])(?=.*[$@$#!%*?&])[A-Za-z\\d$@$#!%*?&]{3,}")
        return passwordTest.evaluate(with: password)
    }
    func isValidEmail(testStr:String) -> Bool {
        // print("validate calendar: \(testStr)")
        let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"

        let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        return emailTest.evaluate(with: testStr)
    }
}

創建UserDetailsVC

import UIKit
import CoreData
class UserDetailsViewController: UIViewController {
    @IBOutlet var nameText: UITextField!
    @IBOutlet var ageText: UITextField!
    @IBOutlet var emailText: UITextField!
    var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    var myStringValue : String?
    override func viewDidLoad() {
        super.viewDidLoad()
     }

    override func viewWillAppear(_ animated: Bool) {
        showData()
        super.viewWillAppear(animated)
    }
    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
    }
    func showData()
    {
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
        request.predicate = NSPredicate (format: "name == %@", myStringValue!)
        do
        {
            let result = try context.fetch(request)
            if result.count > 0
            {
                let nameData = (result[0] as AnyObject).value(forKey: "name") as! String
                let agedata = (result[0] as AnyObject).value(forKey: "age") as! String
                let emaildata = (result[0] as AnyObject).value(forKey: "email") as! String
                nameText.text = nameData
                ageText.text = agedata
                emailText.text = emaildata
            }
        }
        catch {
            //handle error
            print(error)
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM