Swift 如何使用Alamofire等待API响应
如何使用Alamofire在SwiftUI中等待API响应?我已经尝试了一些完成处理,但没有工作Swift 如何使用Alamofire等待API响应,swift,swiftui,alamofire,Swift,Swiftui,Alamofire,如何使用Alamofire在SwiftUI中等待API响应?我已经尝试了一些完成处理,但没有工作 private func loadData(completion : ()->()) { let myURL = makeURL() print("myURL=",myURL) AF.request(myURL, method: .get).responseJSON { (response) in
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")
}
我这样称呼它
Button("Show Insights")
{
self.loadData(completion: {
showView = "NormalView"
})
}
我已经看到,我们也可以使用成功/失败案例,但我不知道如何做该completion()
行必须在闭包内
AF.request(myURL, method: .get).responseJSON { (response) in
...
completion()
}
并放弃SwiftyJSON
,选择Codable
。Alamofire可以使用Codable
直接解码JSON