Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift iOS -how to cancel DispatchGroup() from managing a loop

I loop through several Urls, convert them to Data, then send the data to Firebase Storage and then when everything is done send the gathered info to Firebase Database

I use DispatchGroup()'s .enter() to start the loop and once I send the data to Storage and obtain a value url string absoluteString I use .leave() to start the next iteration.

What I realized is that during the loop, there are several points where errors can occur:

  1. once inside the UrlSession
  2. once inside Storage's .putData function
  3. once inside Storage's .downloadURL(completion:... completion handler
  4. and again if the final downloadURL's ?.absoluteString is nil

If I get an error at any of those points I show an alert function showAlert() that shows the alert and cancel's the UrlSession with session.invalidateAndCancel(). I cancel everything because I want the user to start all over again.

Since the DispatchGroup() is left hanging at .enter(), how do I cancel the DispatchGroup() to stop the loop?

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(){
}
like image 816
Lance Samaria Avatar asked Nov 08 '22 06:11

Lance Samaria


1 Answers

In the comments below the question @rmaddy said "You need to call leave whether is succeeds or not". I did that but the loop still ran and sendDataFromDictToFirebaseDatabase() still fired event hough there was an error.

The only work around I could find was to put the loop inside a function with a completion handler and use a bool to decide wether or not the sendDataFromDictToFirebaseDatabase() should fire:

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

And to use it:

@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)
}
like image 172
Lance Samaria Avatar answered Nov 14 '22 21:11

Lance Samaria