iosswiftuidevice

Where should i put the function?


I created a function which checks whether the iPhone is charging or not using UIDevice. Where should I call the function so that it monitors the status throughout the app session? The Function is called "connectivityStatus", at present it's in viewWillAppear.

Language : Swift 3
Platform : iOS 10 (Using UIDevice)


Solution

  • Or you can use a Timer():

    // in viewDidAppear()
    connectivityStatus()
    var timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(YourClassName.function) , userInfo: nil, repeats: true)
    
    //outside viewDidAppear()
    func function(){
        connectivityStatus()
    }
    

    This check the status every 2 seconds! Hope this Helps!

    NOTE:

    If you decide to update it more often, you can change the value from timeInterval: to a smaller one, but be aware that your app might get slower if a lot of processes are going on!