Search code examples
iosswiftalamofire

Alamofire Appending Data


I have a simple Alamofire request and i'm parsing it with SwiftyJSON. Here is code:

var fetchedData: [TestDB]? = []

func fetchData() {
    Alamofire.request(url!, method: .get).validate().responseJSON { response in
        switch response.result {
        case .success(let value):
            let json = JSON(value)

            self.fetchedData = [TestDB]()

            for dict in json["articles"].array! {

                let data = TestDB()

                if let image = dict["urlToImage"].string {
                    data.imageUrls = image
                }

                if let titlee = dict["title"].string {
                    data.titlee = titlee
                }

                if let desc = dict["description"].string {
                    data.desc = desc
                }

                self.fetchedData?.append(data)
                // If i print fetchedData here, i can see it has right values.
                // print(fetchedData)

            }
        case .failure(let error):
            print(error)
        }
    }
        // If i try to print fetchedData here, it's empty.
}

As i said in code, i can't append and use my datas. I think that's something with Alamofire being asynchronous. But couldn't figure out why. Any help is appreciated. Thanks!


Solution

  • When you use asynchronous method you have some way to proceed, for example:

    • use callback
    • use RAC/observation

    Callback:

    func fetchData(completion: (result: [TestDB]) -> ) {
        Alamofire.request(url!, method: .get).validate().responseJSON { response in
           self.fetchedData = [TestDB]()
           // fill self.fetchedData then:
           completion(self.fetchedData) 
        }
    })
    

    Where you call fetchData:

    self.fetchData(completion: { 
        // update collectionview?
        self.collectionView.reloadData() 
    })
    

    RAC:

    You can find all documentation here.

    Plus:

    Some suggestion:

    • self.fetchedData = TestDB is not necessary, probably is sufficient self.fetchData.removeAll()

    • use ObjectMappar to map any json response to object