【问题标题】:How to wait API response with Alamofire [duplicate]如何使用 Alamofire 等待 API 响应 [重复]
【发布时间】: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"
   })
}

我看到我们也可以使用成功/失败案例,但我不知道该怎么做

【问题讨论】:

    标签: swift swiftui alamofire


    【解决方案1】:

    completion() 行必须闭包内

    AF.request(myURL, method: .get).responseJSON { (response) in
    
       ...
    
       completion()
    }
    

    并放弃SwiftyJSON 以支持Codable。 Alamofire 可以直接用Codable 解码JSON。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-17
      • 2017-01-03
      • 2022-07-01
      • 2011-09-09
      • 2012-09-08
      • 1970-01-01
      • 2017-07-21
      • 2018-08-04
      相关资源
      最近更新 更多