Cherry-pick 7c137ba and update tests.
Cherry-pick 7c137ba and update tests.

matrix-org/matrix-ios-sdk,matrix-org/matrix-ios-sdk,matrix-org/matrix-ios-sdk,matrix-org/matrix-ios-sdk,matrix-org/matrix-ios-sdk