1

我在循环中使用调度组来跟踪一组网络请求,因此当它们全部成功完成时,成功完成处理程序仅返回一次。

但是,如果发生单个故障,我想中止整个操作并仅返回一次故障完成处理程序。我面临的问题是所有失败完成处理程序都会多次返回。这不是我想要的。

我的代码看起来像这样。

class NetworkClient {
    // ...
    func fetchBlogPosts(completion: @escaping (Result<[BlogPost], NetworkClientError>) -> Void) {
        let dispatchGroup = DispatchGroup()
        var blogPosts     = [BlogPost]()
        
        for (index, value) in blogPostJSONURLs.enumerated() {
            dispatchGroup.enter()
            
            guard let jsonURL = URL(string: blogPostJSONURLs[index]) else {
                dispatchGroup.leave()
                completion(.failure(.invalidURL))
                return
            }
            
            let dataTask = URLSession.shared.dataTask(with: jsonURL) { data, response, error in
                if error != nil {
                    dispatchGroup.leave()
                    completion(.failure(.errorReturned))
                    return
                }
                
                guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
                    dispatchGroup.leave()
                    completion(.failure(.serverError))
                    return
                }
                
                guard let data = data else {
                    dispatchGroup.leave()
                    completion(.failure(.noData))
                    return
                }
                
                do {
                    let blogPost = try JSONDecoder().decode(BlogPost.self, from: data)
                    blogPosts.append(blogPost)
                    dispatchGroup.leave()
                } catch {
                    dispatchGroup.leave()
                    completion(.failure(.failedToDecodeJSON))
                }
            }
            
            dataTask.resume()
        }
        
        dispatchGroup.notify(queue: .main) {
            completion(.success(blogPosts))
        }
    }
}
4

0 回答 0