Search code examples
jsonswiftfunctionapialamofire

Alamofire download from JSON API


I'm trying to set text on a label from api, but it seems that the function doesn't even get called. Please refer to the snippet below. Is there anything wrong with it?

EDIT: typealias DownloadComplete = () -> ()

var date: String = ""

override func viewDidLoad() {
    super.viewDidLoad()

    timeLbl.text = date

    // Do any additional setup after loading the view.
}

func downloadTimeData(completed: @escaping DownloadComplete) {
    //Downloading forecast weather data for TableView
    Alamofire.request(APIURL).responseJSON { response in

        let result = response.result

        if let dict = result.value as? Dictionary<String, AnyObject> {
            if let currentDate = dict["fulldate"] as? String {
                self.date = currentDate
                print(self.date)
                print("xxx")
            }
        }
     completed()
    }
}

Solution

  • In the code you posted you are not calling downloadTimeData(completed:) anywhere.

    You can do that in viewDidAppear(_:) for example:

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    
        downloadTimeData { 
            // The request has completed
            timeLbl.text = date
        }
    }
    

    Note that you may need to change the call slightly, depending on how DownloadComplete is defined.