Wednesday, 31 July 2019

Removing viewcontrollers from navigation stack



When session expired move to login page : Removing viewcontrollers from navigation stack

//If session expaired move to login page
if message == "Session Expired" {
    DispatchQueue.main.async {
        //Check navigation stacks
        let navigationArray = self.navigationController?.viewControllers //To get all UIViewController stack as Array
        print(navigationArray!)//Prints navigation stacks

        //Remove all navigations
        self.navigationController!.viewControllers.removeAll()
        //Remoce particular VC navigation
        //self.navigationController?.viewControllers.remove(at: "insert here a number")

        //Check navigation stacks
        let navigationArray2 = self.navigationController?.viewControllers //To get all UIViewController stack as Array
        print(navigationArray2 as Any)//Prints nill

        //Check whether the user logined or not
        UserDefaults.standard.set(false, forKey: "isUserLoggedIn")
        //Clear user defaults
        SharedClass.sharedInstance.clearDataFromUserDefaults()

        let lvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LVC") as! LoginViewController
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.window?.rootViewController = lvc                                
    }
}



What is UIWindow in iOS?



Window property :

var window: UIWindow?

the window property used to present the app’s visual content on the device’s main screen.
Normally, Xcode provides your app's main window. New iOS projects use storyboards to define the app’s views. Storyboards require the presence of a window property on the app delegate object, which the Xcode templates automatically provide. If your app does not use storyboards, you must create this window yourself.



Errors in iOS



Errors : 

1) Expression type '@lvalue CGRect' is ambiguous without more context

Code: 

Wrote this code in JSON response 
if status == "SUCCESS" {
    self.myTableView = UITableView(frame: CGRect(x: 0, y: 0, width: self.subView.frame.width, height: tblViewDescArray.count*50)) //Error comes here self.subView.frame.width
    self.subView.addSubview(self.myTableView)

Solution :  https://stackoverflow.com/questions/51140220/swift-4-expression-type-value-cgrect-is-ambiguous-without-more-context

let width = self.subView.frame.width
                                
self.myTableView = UITableView(frame: CGRect(x: 0, y: 0, width: Int(width), height: self.tblViewDescArray.count*50))

2) Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value


Solution : Here tableView IBOutlet not available in this VC.

Monday, 15 July 2019

Navigation types in iOS



Navigation in normal approach :

let cdplvc = self.storyboard?.instantiateViewController(withIdentifier: "CDPLVC"
self.navigationController?.pushViewController(cdplvc!, animated: false)

In PageViewController : 

let cdplvc = self.storyboard?.instantiateViewController(withIdentifier: "CDPLVC"
//We need to fix it navigation
(UIApplication.shared.keyWindow?.rootViewController as? UINavigationController)?.pushViewController(csvc!, animated: true)


Ex. PageViewController : https://stackoverflow.com/questions/56801714/in-pageviewcontroller-navigation-not-working

Set navigation bar back button :

 In pageViewController :

let csvc = self.storyboard?.instantiateViewController(withIdentifier: "CSVC")
let backButton = UIBarButtonItem()
//backItem.title = "Login"
backButton.barButtonTitle(titleString:"Status”)//Through extension class
(UIApplication.shared.keyWindow?.rootViewController as? UINavigationController)?.self.navigationBar.topItem?.backBarButtonItem = backButton
(UIApplication.shared.keyWindow?.rootViewController as? UINavigationController)?.pushViewController(csvc!, animated: true)

extension UIBarButtonItem {
    func barButtonTitle(titleString:String) { 
        title = titleString
        if UIDevice.current.userInterfaceIdiom == .pad {
            setTitleTextAttributes([NSAttributedString.Key.font: UIFont(name: "Medium", size: 20)!], for: UIControl.State.normal);
        } else {
            setTitleTextAttributes([NSAttributedString.Key.font: UIFont(name: "Medium", size: 15)!], for: UIControl.State.normal);
        }        
    }
}

In Normal approach :

let cdplvc = self.storyboard?.instantiateViewController(withIdentifier: "CDPLVC"
        
let backItem = UIBarButtonItem()
backItem.title = "Login"
self.navigationItem.backBarButtonItem = backItem
//If required font size etc…
if UIDevice.current.userInterfaceIdiom == .pad {
     backItem.setTitleTextAttributes([NSAttributedString.Key.font: UIFont(name: "Medium", size: 20)!], for: UIControl.State.normal);
} else {
     backItem.setTitleTextAttributes([NSAttributedString.Key.font: UIFont(name: "Medium", size: 15)!], for: UIControl.State.normal);
}
        

self.navigationController?.pushViewController(cdplvc!, animated: false)





Make ViewController as Transparent view (Create Transparent view with ViewController)




//create view controller
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CEVC")
       
//remove black screen in background
vc.modalPresentationStyle = .overCurrentContext
//add clear color background
vc.view.backgroundColor = UIColor.black.withAlphaComponent(0.4)
            
//present modal
self.present(vc!, animated: false, completion: nil)



Convert Array, Dictionary into JSON in Swift :



Convert Dictionary into JSON in Swift :

From:  https://stackoverflow.com/questions/29625133/convert-dictionary-to-json-in-swift

let dic = ["2": "B", "1": "A", "3": "C"]
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(dic) {
    if let jsonString = String(data: jsonData, encoding: .utf8) {
        print(jsonString)
    }
}


Convert Array in to JSON in Swift

From :  https://riptutorial.com/ios/example/28692/convert-array-into-json-string

let array = [["prod_uniq" : "5cb5d3aecd4d9"], ["Quantity" : "500"], ["Amount" : "1000"]]
        
let jsonString = convertIntoJSONString(arrayObject: array)
print("jsonString - \(jsonString ?? "Empty JSON")")

        
func convertIntoJSONString(arrayObject: [Any]) -> String? {
        
        do {
            let jsonData: Data = try JSONSerialization.data(withJSONObject: arrayObject, options: [])
            if  let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue) {
                return jsonString as String
            }
            
        } catch let error as NSError {
            print("Array convertIntoJSON - \(error.description)")
        }
        return nil
    }


Call function in iOS



//Eable call function
    @IBAction func onClickCallBtn(_ sender: Any) {
        guard let url = URL(string: "tel://self.mobile") else {
            return //be safe
        }
        
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url)
        } else {
            UIApplication.shared.openURL(url)
        }

    }

Difference between == and ===

Difference between == and === https://stackoverflow.com/questions/24002819/difference-between-and == operator checks if their ...