gpt4 book ai didi

ios - Swift iOS - 如何取消 DispatchGroup() 管理循环

转载 作者:行者123 更新时间:2023-11-28 07:48:00 29 4
gpt4 key购买 nike

我循环遍历几个 Url,将它们转换为 Data,然后将数据发送到 Firebase Storage,然后在一切完成后发送收集到 Firebase 数据库

的信息

我使用 DispatchGroup() 的 .enter() 开始循环,一旦我将数据发送到 Storage 并获得值 url 字符串 absoluteString 我使用 .leave() 开始下一次迭代。

我意识到在循环过程中,有几个点可能会发生错误:

  1. 一旦进入 UrlSession
  2. 一旦进入 Storage 的 .putData 函数
  3. 一旦进入 Storage 的 .downloadURL(completion:... 完成处理程序
  4. 如果最终的 downloadURL 的 ?.absoluteString 是 nil

如果我在这些点中的任何一个点出现错误,我会显示一个警报函数 showAlert(),它会显示警报并使用 session.invalidateAndCancel() 取消 UrlSession。我取消了所有内容,因为我希望用户重新开始。

由于 DispatchGroup() 在 .enter() 处挂起,我该如何取消 DispatchGroup() 来停止循环?

var urls = [URL]()
var picUUID = UUID().uuidString
var dict = [String:Any]()

let session = URLSession.shared
let myGroup = DispatchGroup()
var count = 0

for url in urls{

myGroup.enter()
session.dataTask(with: url!, completionHandler: {
(data, response, error) in

if error != nil {
self.showAlert() // 1st point of error
return
}

DispatchQueue.main.async{
self.sendDataToStorage("\(self.picUUID)_\(self.count).jpg", picData: data)
self.count += 1
}
}).resume()

myGroup.notify(queue: .global(qos: .background) {
self.sendDataFromDictToFirebaseDatabase()
self.count = 0
self.session.invalidateAndCancel()
}
}

func sendDataToStorage(_ picId: String, picData: Data?){

dict.updateValue(picId, forKey:"picId_\(count)")

let picRef = storageRoot.child("pics")
picRef.putData(picData!, metadata: nil, completion: { (metadata, error) in

if error != nil{
self.showAlert() // 2nd point of error
return
}

picRef?.downloadURL(completion: { (url, error) in

if error != nil{
self.showAlert() // 3rd point of error
return
}

if let picUrl = url?.absoluteString{

self.dict.updateValue(picUrl, forKey:"picUrl_\(count)")
self.myGroup.leave() //only leave the group if a Url string was obtained
}else{
self.showAlert() // 4th point of error
}
})
})
}

func showAlert(){
// the DispatchGroup() should get cancelled here
session.invalidateAndCancel()
count = 0
UIAlertController...
}

func sendDataFromDictToFirebaseDatabase(){
}

最佳答案

在问题下方的评论中,@rmaddy 说“无论成功与否,您都需要调用 leave”。我这样做了,但循环仍在运行并且 sendDataFromDictToFirebaseDatabase() 仍然触发事件,尽管出现错误。

我能找到的唯一解决方法是将循环放在一个带有完成处理程序的函数中,并使用 bool 来决定 sendDataFromDictToFirebaseDatabase() 是否应该火:

var urls = [URL]()
var picUUID = UUID().uuidString
var dict = [String:Any]()

let session = URLSession.shared
let myGroup = DispatchGroup()
var count = 0
var wasThereAnError = false // use this bool to find out if there was an error at any of the error points

func loopUrls(_ urls: [URL?], completion: @escaping ()->()){

for url in urls{

myGroup.enter()
session.dataTask(with: url!, completionHandler: {
(data, response, error) in

if error != nil {
self.showAlert() // 1st point of error. If there is an error set wasThereAnError = true
return
}

DispatchQueue.main.async{
self.sendDataToStorage("\(self.picUUID)_\(self.count).jpg", picData: data)
self.count += 1
}
}).resume()

myGroup.notify(queue: .global(qos: .background) {
completion()
}
}
}

// will run in completion handler
func loopWasSuccessful(){

// after the loop finished this only runs if there wasn't an error
if wasThereAnError == false {
sendDataFromDictToFirebaseDatabase()
count = 0
session.invalidateAndCancel()
}
}

func sendDataToStorage(_ picId: String, picData: Data?){

dict.updateValue(picId, forKey:"picId_\(count)")

let picRef = storageRoot.child("pics")
picRef.putData(picData!, metadata: nil, completion: { (metadata, error) in

if error != nil{
self.showAlert() // 2nd point of error. If there is an error set wasThereAnError = true
return
}

picRef?.downloadURL(completion: { (url, error) in

if error != nil{
self.showAlert() // 3rd point of error. If there is an error set wasThereAnError = true
return
}

if let picUrl = url?.absoluteString{

self.dict.updateValue(picUrl, forKey:"picUrl_\(count)")
self.myGroup.leave() // leave group here if all good on this iteration
}else{
self.showAlert() // 4th point of error. If there is an error set wasThereAnError = true
}
})
})
}

func showAlert(){
wasThereAnError = true // since there was an error set this to true
myGroup.leave() // even though there is an error still leave the group
session.invalidateAndCancel()
count = 0
UIAlertController...
}

func sendDataFromDictToFirebaseDatabase(){
}

并使用它:

@IBAction fileprivate func postButtonPressed(_ sender: UIButton) {    

wasThereAnError = false // set this back to false because if there was an error it was never reset

loopUrls(urls, completion: loopWasSuccessful)
}

关于ios - Swift iOS - 如何取消 DispatchGroup() 管理循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50478833/

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