I loop through several Url
s, 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:
UrlSession
.putData
function.downloadURL(completion:...
completion handler?.absoluteString
is nilIf 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(){
}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With