【发布时间】:2021-03-22 14:53:39
【问题描述】:
如何使用 Alamofire 在 SwiftUI 中等待我的 API 响应?我已经尝试了一些完成处理但没有工作。
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"
})
}
我看到我们也可以使用成功/失败案例,但我不知道该怎么做
【问题讨论】: