I am making an app where I have to check for login status first and then have to decide which ViewController to present. And because I have to use a lot of URLs to hit and get value throughout the project, I have made a separate file. That file takes the URL and returns the Dictionary
which I need.
I call the method at viewDidLoad
and use the value in other function called handleData
. But every time handleData
gets executed before the function in the separate class. Is there a solution for this so that I can have functions execute in desired order?
Here are the snippets:
class LoadingViewController: UIViewController {
@IBOutlet var activity: UIActivityIndicatorView!
let fetchData = FetchingData()
var ifHasAccount: NSDictionary!
var acStatus: String?
override func viewDidLoad() {
super.viewDidLoad()
handleData()
ifHasAccount = NSDictionary()
activity.startAnimating()
}
func handleData(){
fetchData.urlForHit = "Some URL"
ifHasAccount = fetchData.fetchData()
print(ifHasAccount)
}
}
and for the other class i.e.,
FetchingData()
it is:
class FetchingData{
private var _urlForHit: String?
var _aDictionary: NSDictionary?
var urlForHit: String{
get{
return _urlForHit!
}
set{
_urlForHit = newValue
}
}
func fetchData() -> NSDictionary {
var aDictionary = NSDictionary()
let urlToHit = URL(string: _urlForHit!)
var request = URLRequest(url: urlToHit!)
request.setValue(UserDefaults.standard.value(forKey: "DEVICEID")! as? String, forHTTPHeaderField: "deviceId")
request.setValue(UserDefaults.standard.value(forKey: "FCMID")! as? String, forHTTPHeaderField: "fcmId")
request.setValue("iOS", forHTTPHeaderField: "deviceType")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil{
print((error?.localizedDescription)!)
return
}
guard let response = response as? HTTPURLResponse, 200..<300 ~= response.statusCode else {print("Response out of range"); return}
if data != nil{
do{
aDictionary = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
print(aDictionary)
}
}
else
{
print("Data nil")
}
}
task.resume()
self._aDictionary = aDictionary
return _aDictionary!
}
}