I am learning the AFNetworking, but I can't get the data. The json data is good, the output of print in dataHttpRequest() is 10, but the output of print in viewWillAppear always is 0.

I have googled for two days, maybe something about escaping closures? But I don't know how to get the data yet.

Any help? Thanks.

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)");
    }
    }
}

0 Answers