gpt4 book ai didi

ios - 判断urlsession.shared和Json解析完成的时间

转载 作者:行者123 更新时间:2023-11-28 20:56:10 24 4
gpt4 key购买 nike

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

一切正常,但我想获取所有要下载的文件的大小。

但是我在设置一个指示一切都已完成的完成 block 时遇到了一些麻烦。

这是代码。

   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()
}

当一切都完成后,我想在最后得到数组的总和,现在 print(self.sum) 正在运行并显示 0。

我不熟悉完成,我确信我做错了。

最佳答案

您需要 DispatchGroup

在调用内部异步任务enter之前,在内部异步任务的完成 block 中leave组。
最后当组通知时,调用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()
}

关于ios - 判断urlsession.shared和Json解析完成的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52205834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com