问题
In my project app I use Firebase Storage and Database simultaneously. I would like to use transactions concept, however I have never used it before so it's not obvious for me. Users are allowed to upload a file to the server. I track these uploads in database (assigning url's of the uploaded file to the user). So I perform 2 actions at the same time:
uploading the file
updating database
I wanna be sure that if any of those actions fails, none is performed (e.g. Internet connection is down). I need some tips on how to handle exceptions like the one mentioned before and how to implement it in appropriate way as it is crashing at the moment. Here is the code I have:
newRef.runTransactionBlock({ (currentData: MutableData) ->
TransactionResult in
let uploadTask = ref.putData(contents as Data, metadata:
self.myMetadata, completion: { (metadata, error) in
if error != nil {
...
}
DataService.instance.usersRef.observeSingleEvent(of: .value) {
(snapshot: DataSnapshot) in
...
_ = DataService.instance.usersRef.child("\
(key)/profile/myURLS").updateChildValues([ strEncoded as!
AnyHashable : downloadURL])
}
}
return TransactionResult.success(withValue: currentData)
})
{ (error, committed, snapshot) in
if let error = error {
print(error.localizedDescription)
}
}
Thanks in advance!
回答1:
Transactions only run within the context of the database where the transaction is started. The all-or-none behavior of transactions only applies to the work that you do within the database itself, not any external properties. Your transaction handlers should be as fast as possible and not block on other work.
The usual practice for file uploads is to perform the file upload first, then after that succeeds, write to the database.
来源:https://stackoverflow.com/questions/48772797/using-transactions-in-firebase