首页 > 解决方案 > 如何在 iOS 中使用 Sqllite 验证登录表单进入下一页?

问题描述

**this is to how to create a login validation form to move from login to next view controller **

      **fetching the data from database** 
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
                         return
                     }
    **it stores the data** 
                    let managedContext = appDelegate.persistentContainer.viewContext
                     //it fetches the data
                     let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Details")

         **validation code to check it but the condition fails**

                 do {
                            let result = try managedContext.fetch(fetchRequest)
                            for data in result as! [NSManagedObject] {
                            if ([emailid.text].count != 0  && [password.text].count != 0){
                            if (emailid.text  == data.value(forKey: "emailId") as? String) && (password.text  == data.value(forKey: "passWord") as? String){
                                let secondvc = storyboard?.instantiateViewController(withIdentifier: "loginVcID") as! loginVc
                                       self.navigationController?.pushViewController(secondvc, animated: true)


           }

在这种情况下,它不会移动到下一个视图控制器 来检查另一个条件 } else { self.label.text = "enter a valid data" } }

                        }
    **when it fails it goes to catch to show that**
                   catch
                    {

                            print("Failed")
                        }
                    }



        }

     **this code is for registration to save into database**
        **to create a database and store the value**
         guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
         let managedContext = appDelegate.persistentContainer.viewContext
         let detailEntity = NSEntityDescription.entity(forEntityName: "Details", in: managedContext)!

** 创建数据库** let detail = NSManagedObject(entity: detailEntity, insertInto: managedContext) detail.setValue(username.text, forKeyPath: "userName") detail.setValue(emailid.text, forKey: "emailId") detail. setValue(password.text, forKey: "passWord") detail.setValue(city.text, forKey: "city")

    **saving the data** 
          do {

                        try managedContext.save()
                        }

                 ** it display whatever in that method**
            catch let error as NSError

            {  

它在失败时显示错误 print("Could not save. (error), (error.userInfo)") }

标签: iosvalidation

解决方案


转到你的 appDelegate,你会发现一行 // MARK: - Core Data stack & // MARK: - Core Data Saving support, remove the saveContext() function & also remove persistentContainer.. 然后

将此类添加到您的项目中

final class PersistenceManager {

private init() {}

static let shared = PersistenceManager()


// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
    */
    let container = NSPersistentContainer(name: "ProjectNAME")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

lazy var context = persistentContainer.viewContext

// MARK: - Core Data Saving support

func save() {
    if context.hasChanges {
        do {
            try context.save()                
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

func fetch<T: NSManagedObject>(_ objectType: T.Type) ->  [T] {
    let entityName = String(describing: objectType)
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
    do {
        let fetchedObjects = try context.fetch(fetchRequest) as? [T]
        return fetchedObjects ?? [T]()
    } catch {
        return [T]()
    }
}

func deleteAll<T: NSManagedObject>(_ objectType: T.Type) {
    let entityName = String(describing: objectType)
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
    do {
        try persistentContainer.persistentStoreCoordinator.execute(deleteRequest, with: context)
    } catch {
        print(error.localizedDescription)
    }
}

func delete(_ object: NSManagedObject) {
    context.delete(object)
    save()
}

}

获取数据

PersistenceManager.shared.fetch(User.self)

删除数据

PersistenceManager.shared.delete(user)

创建用户

let newUser = Users(context: PersistenceManager.shared.context)
newUser.name = "Zero Cool"
newUser.password = "qwerty"
PersistenceManager.shared.save()

推荐阅读