Reputation: 3
Today I am using Alamofire to extract an int value. It's pulling the int fine, but I want to save the int value outside of the request (in a different function, viewDidLoad()).
I'm not sure how to call the completion handler, it doesn't seem to be doing anything at the moment.
Here is the method that extracts the int value in question (lastModified).
func checkVersion(completion: @escaping (Int) -> Void) {
Alamofire.request(versionCheckEndpoint).responseJSON { response in
if(response.result.value != nil) {
let json = JSON(response.result.value!)
self.s3Endpoint = json["s3BucketURL"].stringValue
let lastModified = json["lastModified"].intValue
self.latestVersion = lastModified
}
}
}
I tried saving the value to an instance variable, this doesn't work.
I called the completion handler like this in viewDidLoad().. but I'm positive it's nowhere near correct:
self.checkVersion() { response in
self.latestVersion = response
}
Can anyone give me some insight on how I can save the int value for lastModified to some local variable so it is not contained within the scope of the Alamofire request?
Upvotes: 0
Views: 1374
Reputation: 5259
In the function checkVersion
the completion block isn't called.
You must call it after retrieving the value (although I would suggest to make it optional)
func checkVersion(_ completion: @escaping (Int?) -> Void) {
Alamofire.request(versionCheckEndpoint).responseJSON { response in
guard let value = response.result.value else {
completion(nil)
return
}
let json = JSON(value)
self.s3Endpoint = json["s3BucketURL"].stringValue
let lastModified = json["lastModified"].intValue
completion(lastModified)
}
}
And call it like this:
self.checkVersion() { value in
guard let value = value else {
//handle invalid values here
return
}
latestVersion = value
// update the view if needed
}
Upvotes: 1