Search code examples
iosswiftuitabbarcontrollerseguecloudkit

How to condition segues using CloudKit query?


I created a login page backed up by CloudKit. I want to know how to create a conditioned segue if the login has a certain value, and then direct the user to a View Controller based on that value

In details, I have three Segues I want to connect:

sign in id segue:LoginSuccessSegue

staff tab bar id segue:idStaffTabBar

student tab bar id segue:idStudentTabBar

First Segue LoginSuccessSegue: the sign in view controller has a show segue id LoginSuccessSegue the connects to staff tab bar controller and student tab bar controller.

Second Segue idStaffTabBar: After queryProfileType() is executed, it will look for the profile type in a list to check if the user profile is a teacher value or something else. Then if that is true "LoginSuccessSegue" will automatically take the user to staff tab bar controller, "StaffBookedVC.self" by usingits segueidStaffTabBar `

Third Segue idStudentTabBar: if the user is not a teacher then after pressing the sign in button redirect to student tab bar controller, "stdBookingVC.self" by using idStudentTabBar or

How can I achieve an automatic conditional sign in in multiple views suing segues and cloud kit query?

This is the code for the sign-in button:

@IBAction func btnSignInTapped(sender: UIButton)
{
    let userEmailAddress = userEmailAddressTextField.text
    let userPassword = userPasswordTextField.text


    if(userEmailAddress!.isEmpty || userPassword!.isEmpty)
    {
        notifyUser("Empty fields", message: "all fields are required")
    }
    print("fetching is in progress")

    queryProfileType()

    print("\nfetching had stopped")
}//end of signInbtn

func queryProfileType()
{
    queryCredentials()

    print("\nProfile Query starting")
    //execute query
    let organizers = ["Teacher || Youtuber || Instagrammer || "]
    let predicate = NSPredicate(format: "ProfileType = '\(organizers)' ")
    print("\nThis is the predicate\n\(predicate)")
    let query = CKQuery(recordType: "RegisteredAccounts", predicate: predicate)
    publicDatabase!.performQuery(query, inZoneWithID: nil) { results, error in
        if (error != nil)
        {
            print(error)
        }else
            {

                if (results! == organizers)
                {
                    self.performSegueWithIdentifier("idStaffTabBar", sender: StaffBookedVC.self)
                }else{
                    self.performSegueWithIdentifier("idStudentTabBar", sender: stdBookingVC.self)

                }
                print("\(results)\nthese are the printed results")
            }

        }
    let firstFetch = CKFetchRecordsOperation()
    let secondFetch = CKFetchRecordsOperation()
    secondFetch.addDependency(firstFetch)

    let queue = NSOperationQueue()
    queue.addOperations([firstFetch, secondFetch], waitUntilFinished: false)
}

here is a picture of the storyboard segues Storyboard

if your answer will contain these methods, please show me some examples: shouldPerformSegueWithIdentifier and prepareForSegue

this did not work from me either

self.presentViewController(SignInNavigationVCTabBars, animated: true,
                { results, error in

                if (results! == organizers)
                {
                    self.performSegueWithIdentifier("idStaffTabBar", sender: StaffUITABbarVC.self)

                }else{
                    self.performSegueWithIdentifier("idStudentTabBar", sender: StdUITABbarVC.self)

                }
            }

`


Solution

  • Here is the answer

    I did not expect valueforkey would have it all what can I see? never stop trying

     //log in function
    func queryCredentials()
    {
        print("*********\nQueryCredentials starting")
    
        // System indicator
        let spinningActivity = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
        spinningActivity.labelText = "Signing in"
        spinningActivity.detailsLabelText = "Please wait"
    
    
        // querying predicate in cloud kit to check via email and password property
        let predicate = NSPredicate(format: "Email = %@", userEmailAddressTextField.text!)
        let query = CKQuery(recordType: "RegisteredAccounts", predicate: predicate)
        publicDatabase?.performQuery(query, inZoneWithID: nil,
            completionHandler: ({results, error in
    
                if (error != nil)
                {
                    dispatch_async(dispatch_get_main_queue())
                        {
                        // if the user is not signed, display this error
                        self.notifyUser("Cloud Access Error",
                            message: "to fix this error Sign in you icloud \n go to settings\nthen sign in icloud account\n error code:\(error!.localizedDescription)")
                        }
                }else
                {
                    if (results!.count > 0)
                    {
                        // the results after success case of the query
                        let record = results![0] as! CKRecord
    
                        // read from the result to navigate via profiletype attribute
                        let proftype = record.valueForKey("ProfileType") as! String
    
                        switch proftype
                        {
                        case("Teacher"):
                            self.staffView()
                            break;
    
                        case("Manager"):
                            self.staffView()
                            break;
    
                        case("Student"):
                            // stdView() is a student coded segue as a function to navigate to student view
                            self.stdView()
                            break;
    
                        case("Worker"):
                            self.stdView()
                            break;
    
                        default:
                            break;
    
                        }
                        self.currentRecord = record
    
                        dispatch_async(dispatch_get_main_queue())
                            {
                            // if credentials are correct, display you are logged in
                            self.userPasswordTextField!.text =
                                record.objectForKey("Password") as! String
                            self.notifyUser("Welcome", message: "You are loogedin")
    
                            }
                    }else
                    {
                        dispatch_async(dispatch_get_main_queue())
                            {
                            self.notifyUser("No Match Found",
                                message: "No record matching")
                            }
                    }
                }
    
            }))
        // hiding indicator
        spinningActivity.hide(true)
    }