0

How to hide and show the button in viewcontroller, for example UserRole = "Admin" show the button and UserRole="User" hide the button. I have written the code in AppDelegate class below and how to write method in view controller class hide and show buttonMethod name is: isItAdminOrNot

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
    //var email = (String)()

    if (error == nil) {
        let givenName = user.profile.name
        let email = user.profile.email

        let param = ["UserName": givenName!, "Email": email!] as Dictionary<String, String>

        let request = NSMutableURLRequest(url: NSURL(string: "http://beta.json-generator.com/api/json/get/EJoC6gB_z")! as URL)

        let session = URLSession.shared
        request.httpMethod = "POST"

        //Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.httpBody = try! JSONSerialization.data(withJSONObject: param, options: [])

        let task = session.dataTask(with: request as URLRequest) { data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }

            do {
                if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject] {

                    print("Response: \(json)")

                    let USerresponse = json["UserRole"] as! String
                    print(USerresponse)
                    DispatchQueue.main.async {
                        // now update UI on main thread

                        DispatchQueue.main.async {
                            // now update UI on main thread
                            self.userRoleValue(userRole: USerresponse)
                        }
                    }
                } else {
                    let jsonStr = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) // No error thrown, but not NSDictionary
                    print("Error could not parse JSON: \(jsonStr)")


                    if let data1 = jsonStr?.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) {

                        do {
                            if let dictionary = try JSONSerialization.jsonObject(with: data1, options: JSONSerialization.ReadingOptions.mutableContainers) as? [AnyObject] {

                                let arrayVlaues = dictionary as Array
                                print(arrayVlaues[0])
                                let userRole = arrayVlaues[0].value(forKey: "UserRole") as! String

                                DispatchQueue.main.async {
                                    // now update UI on main thread
                                    self.userRoleValue(userRole: userRole)
                                }


                            }
                        }
                    }

                }
            } catch let parseError {
                print(parseError)// Log the error thrown by `JSONObjectWithData`
                let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                print("Error could not parse JSON: '\(jsonStr)'")
            }
        }

        task.resume()

        // ...
    } else {
        print("\(error.localizedDescription)")
    }
}

func userRoleValue(userRole: String) {
    if(userRole == "User") {
        self.loadParticlularController(value: 1)
    } else if(userRole == "Admin") {
        self.loadParticlularController(value: 2)
    } else if(userRole == "NewUser") {
        self.loadParticlularController(value: 0)
    }
}

func loadParticlularController(value: Int) {
    print(value)

    let myStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    var pageNav: UINavigationController;
    let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate

    // New User
    if (value == 0) {
        let homePage = myStoryBoard.instantiateViewController(withIdentifier: "ApprovalUser") as! ApprovalUser

        pageNav = UINavigationController(rootViewController: homePage)
        appDelegate.window?.rootViewController = pageNav
    } else if(value == 1) { // Existing User
        let homePage = myStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController

        homePage.isItAdminOrNot(val: false)

        pageNav = UINavigationController(rootViewController: homePage)
        appDelegate.window?.rootViewController = pageNav
    } else if(value == 2) { // Existing User with Admin
        let homePage = myStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
        homePage.isItAdminOrNot(val: true)

        pageNav = UINavigationController(rootViewController: homePage)
        appDelegate.window?.rootViewController = pageNav
    }
}
krlzlx
  • 5,752
  • 14
  • 47
  • 55

2 Answers2

0

Try like,

If then name of button is homePageButton then,

homePageButton.isHidden = true
homePageButton.isHidden = false

in HomeViewController's viewDidLoad or viewWillAppear method to show/hide button.

ERbittuu
  • 968
  • 8
  • 19
0

Under your

homePage.isItAdminOrNot(val: false)

Add this:

homePage.button.isHidden = true
  • Thanks, but how to write in these code boolean type function isItAdminOrNot{ } –  Feb 13 '17 at 08:58
  • isItAdminOrNot is your HomeViewController class's property because I saw you set it here: let homePage = myStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController homePage.isItAdminOrNot(val: false) – Nguyễn Anh Việt Feb 13 '17 at 09:07
  • you already set isItAdminOrNot in your appDelegate.swift file – Nguyễn Anh Việt Feb 13 '17 at 09:10
  • but how to declare is ItAdminOrNot func in HomeViewController,these code raises issue (Bool)-> is not convertible 'Bool' if isItAdminOrNot { button.hidden = false } else { button.hidden = true } –  Feb 13 '17 at 09:13
  • Can you post your HomeViewController file? Just your isItAdminOrNot function is enough – Nguyễn Anh Việt Feb 13 '17 at 09:40
  • class HomeViewController: UIViewController,GIDSignInUIDelegate { @IBOutlet weak var apps: UIButton! override func viewDidLoad() { super.viewDidLoad() GIDSignIn.sharedInstance().uiDelegate = self if isItAdminOrNot { button.hidden = false } else { button.hidden = true } } } –  Feb 13 '17 at 09:44
  • Try this way: under this line im your appDelegate file... homePage.isItAdminOrNot(val: false) add this.. homePage.buttom.isHidden = true... – Nguyễn Anh Việt Feb 13 '17 at 10:06
  • Hi but it raises issue "unexpectedly found nil while unwrapping an optional value" –  Feb 13 '17 at 10:31