我正在学习AFNetworking,但无法获取数据。 json数据很好,dataHttpRequest()中print的输出为10,但是print的输出 在viewWillAppear中始终为0。
我已经在Google上搜索了两天,也许是关于逃避闭包?但是我还不知道如何获取数据。
有帮助吗?谢谢。
import UIKit
import AFNetworking
import SwiftyJSON
class TestViewController: UIViewController {
var viewModels: [Int]=[]
override func viewWillAppear(_ animated: Bool) {
self.dataHttpRequest()
print(viewModels.count)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func dataHttpRequest() {
let urlStr = "http://192.168.1.108/test.json";
//AFNetworking
let sessionManager = AFHTTPSessionManager.init();
sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain");
sessionManager.get(urlStr, parameters: nil, progress: nil, success: { (_, responseObject) -> Void in
guard responseObject != nil else{
print("nil");
return;
};
let json = JSON(responseObject as Any)
for (_, _):(String, JSON) in json {
self.viewModels.append(1)
}
print(self.viewModels.count)
}) { (_, error) in
print("...........\(error)");
}
}
}