在其他Alamofire请求中等待Alamofire请求完成

时间:2017-12-19 21:03:40

标签: swift alamofire

我不知道下面的代码是否是最好的方法,但我需要做一个Alamofire请求然后遍历JSON对象以获取每个对象的url图像然后将图像保存在我的帖子中对象数组。 fetchMedia返回一个UIImage,在这个函数中还有另一个获取图像的Alamofire请求。

当然post.thumbnail总是为nil,因为在第二个请求完成之前,post对象被附加到我的数组中。

我该如何解决这个问题?

Alamofire.request(url, method: .get)
        .validate()
        .responseJSON { response in
            switch response.result {
            case .success(let value):
                let json = JSON(value)
                for (_,subJson):(String, JSON) in json {
                    var post = Post()
                    // Fetch the title
                    if let title = subJson["title"]["rendered"].string {
                        post.title = title
                    }
                    // Fetch the the thumbnail for the cell
                    if let url = subJson["_links"]["wp:featuredmedia"][0]["href"].url {
                        post.thumbnail = self.fetchMedia(url: url)
                    }
                    if post.title != nil {
                        self.posts.append(post)
                        self.collectionView?.reloadData()
                    }
                }
            case .failure(let error):
                print(error)
                // Do something if there's an error in the response
                // Maybe load the latests posts from the database
            }
    }

0 个答案:

没有答案