我正在创建一个应用程序,我必须首先检查登录状态,然后必须决定要呈现哪个ViewController。而且因为我必须使用大量的URL才能在整个项目中获得并获得价值,所以我制作了一个单独的文件。该文件获取URL并返回我需要的Dictionary
。
我在viewDidLoad
调用该方法,并使用名为handleData
的其他函数中的值。但每次handleData
在单独的类中的函数之前执行。有没有解决方案,以便我可以按所需的顺序执行功能?
以下是摘录:
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)
}
}
和其他类,即
FetchingData()
它是:
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!
}
}