代码之家  ›  专栏  ›  技术社区  ›  Julien7377

确定何时urlsession.shared文件和Josn解析完成

  •  0
  • Julien7377  · 技术社区  · 6 年前

    我正在下载并读取一个json文件。这个json包含文件列表及其在服务器上的地址。

    但是我在设置一个completionblock时遇到了一些麻烦,它会指示所有的事情都完成了。

       jsonAnalysis {
            self.sum = self.sizeArray.reduce(0, +)
            print(self.sum)
        } here
    
    func jsonAnalysis(completion:  @escaping () -> ()) {
    
    
        let urlString = "xxxxxxxxxxxxxxxxxxxxx"
        let url = URL(string: urlString)
        URLSession.shared.dataTask(with:url!) { (data, response, error) in
            if error != nil {
                print("error")
    
            } else {
                do {
    
                    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: Any]
                    self.i = -1
                    guard let array = json?["Document"] as? [Any] else { return }
    
                    for documents in array {
    
                        self.i = self.i + 1
                        guard let VersionDictionary = documents as? [String: Any] else { return }
                        guard let DocumentName = VersionDictionary["documentname"] as? String else { return }
                        guard let AddressServer = VersionDictionary["addressserver"] as? String else { return }
    
                        self.resultAddressServer.append(AddressServer)
                        self.addressServer = self.resultAddressServer[self.i]
                        self.resultDocumentName.append(DocumentName)
                        self.documentName = self.resultDocumentName[self.i]
    
                        let url1 = NSURL(string: AddressServer)
                        self.getDownloadSize(url: url1! as URL, completion: { (size, error) in
                            if error != nil {
                                print("An error occurred when retrieving the download size: \(String(describing: error?.localizedDescription))")
                            } else {
                                self.sizeArray.append(size)
                                print(DocumentName)
                                print("The download size is \(size).")
    
                            }
                        })
    
                    }
    
                } catch {
                    print("error")
                }
    
            }
                completion()
    
            }   .resume()
    
    }
    
    func getDownloadSize(url: URL, completion: @escaping (Int64, Error?) -> Void) {
        let timeoutInterval = 5.0
        var request = URLRequest(url: url,
                                 cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
                                 timeoutInterval: timeoutInterval)
        request.httpMethod = "HEAD"
        URLSession.shared.dataTask(with: request) { (data, response, error) in
            let contentLength = response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
            completion(contentLength, error)
            }.resume()
    }
    

    我想在最后得到数组的总和,当一切都完成后,马上打印(自我总和)正在运行并显示0。

    1 回复  |  直到 5 年前
        1
  •  2
  •   vadian    6 年前

    DispatchGroup .

    在调用内部异步任务之前 enter ,位于内部异步任务的完成块中 leave 小组。
    最后当团队 notifies ,呼叫 completion

    let group = DispatchGroup()
    for documents in array {
        ...
    
        let url1 = URL(string: AddressServer) // no NSURL !!!
        group.enter()
        self.getDownloadSize(url: url1!, completion: { (size, error) in
             if error != nil {
                print("An error occurred when retrieving the download size: \(String(describing: error?.localizedDescription))")
             } else {
                self.sizeArray.append(size)
                print(DocumentName)
                print("The download size is \(size).")
             }
             group.leave()
         })
    }
    group.notify(queue: DispatchQueue.main) {
        completion()
    }