Wednesday, September 26, 2018

Swift - App is currently in Main Thread or not


At any point of time, we can check whether we are in main thread or not.


     
    if Thread.current.isMainThread {
        print("isMainThread")
    }

  
This is useful for generic UI operations for async calls.

Suppose, we are need to display generic alerts for network errors and we wrote a common method for that,


     
   func networkError() {
        //stop loader
        //display alert
    }



Some developers forget to write UI calls on main thread in network calls.


     
 let task = URLSession.shared.dataTask
  (with: url) { ( data, responseData, error) in
                 
            if error != nil {
                networkError()
            }

        }



So, We can check whether we are in main thread or not in  networkError() method and do UI stuff like shown below.


     
 func networkError() {

        if Thread.current.isMainThread {
            //stop loader
            //display alert
        } else {
            DispatchQueue.main.async {
                //stop loader
                //display alert
            }
        }
    }



Hope this post is useful. Feel free to comment incase of any queries.



1 comment:

  1. As for me, many of these things are still incomprehensible, but maybe someday I will understand it. I like the most to use proven applications that work in the cloud and I can work on them from anywhere. If you want to read about them, I think you'll like it very much.

    ReplyDelete