Search code examples
arraysjsonswiftparsingalamofire

How to save response.result.value from Alamofire in local array swift 3


Alamofire.request(NEWS_FEED_URL).responseJSON { response in

guard let newsResponse = response.result.value else{
        print("Error: \(response.result.error)")
        return
    }
    print("JSON: \(newsResponse)")
    let localArray:Array = [newsResponse]
    print("Local Array:", localArray)
}



I am using alamofire to fetch data from server and trying to write parser on the response data. When I fetch response.result.value from alamofire and print it is working fine. But as soon as I put response.result.value in my local array it gives  


[<__NSArrayI 0x6080000bcf80>(
{
    category = World; 
})]

and so on as result (Console). Also I am unable to convert response value of type 'Any' to 'Array'. Please help me how to add response.result.value in local array of type 'Array'. Can someone explain something about type casting on alamofire in brief?


Solution

  • You need to simply cast the result of response.result.value to Array of Dictionary.

    guard let newsResponse = response.result.value as? [[String:String]] else{
        print("Error: \(response.result.error)")
        return
    }
    print("JSON: \(newsResponse)")
    let localArray = newsResponse
    //Access the localArray
    print("Local Array:", localArray)
    //Now to get the desired value from dictionary try like this way.
    let dic = localArray[0]
    let title = dic["title"] ?? "Default Title"
    let link = dic["link"] as? "Default link"
    //... get other value same way.
    

    Note : Your response is already an Array so don't make array from it by adding it inside another array.