how can I wait my API response in SwiftUI using Alamofire ? I've already tried some completion handling but not working.
private func loadData(completion : ()->()) {
let myURL = makeURL()
print("myURL=",myURL)
AF.request(myURL, method: .get).responseJSON { (response) in
if response.value != nil {
let userJSON: JSON = JSON(response.value!)
print("userJSON: ", userJSON)
newName = userJSON["name"].stringValue
image = userJSON["image"].stringValue.replacingOccurrences(of: "\\/\\/", with: "//")
print("image = ", image)
numShare = userJSON["numShares"].intValue.shorted()
engagementRate = userJSON["engagementRate"].intValue.shorted()
followers = userJSON["followers"].intValue.shorted()
numLikes = userJSON["numLikes"].intValue.shorted()
numViews = userJSON["numViews"].intValue.shorted()
numVideos = userJSON["numVideos"].intValue.shorted()
numComments = userJSON["numComments"].intValue.shorted()
following = userJSON["following"].intValue.shorted()
//update
} else {
print("err, \(String(describing: response.error))")
}
}
completion()
print("ok")
}
Here is how I call it
Button("Show Insights")
{
self.loadData(completion: {
showView = "NormalView"
})
}
I've seen that we can also use success/failure cases but I don't know how to do it
The completion()
line must be inside the closure
AF.request(myURL, method: .get).responseJSON { (response) in
...
completion()
}
And drop SwiftyJSON
in favor of Codable
. Alamofire can decode JSON with Codable
directly.